aboutsummaryrefslogtreecommitdiff
path: root/wrapper.go
blob: 8058a2765334ffadecac6c8a6b126124df8c5429 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package jsonrpc2

import (
	"context"
	"encoding/json"
)

func Wrap[RQ any, RS any](handler func(context.Context, *RQ) (RS, error)) Handler {
	return func(ctx context.Context, in json.RawMessage) (json.RawMessage, error) {
		req := new(RQ)
		if err := json.Unmarshal(in, req); err != nil {
			return nil, NewError(ErrCodeParseError)
		}
		resp, err := handler(ctx, req)
		if err != nil {
			return nil, Error{
				Code:    ErrUser,
				Message: err.Error(),
			}
		}
		return json.Marshal(resp)
	}
}

type Handler func(context.Context, json.RawMessage) (json.RawMessage, error)