-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
93 lines (78 loc) · 1.98 KB
/
response.go
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package jsonrpc
import (
"encoding/json"
"github.com/juju/errors"
)
func ResponseStringId(id string) ResponseOption {
return func(opts *ResponseOptions) error {
bytes, err := json.Marshal(id)
if err != nil {
return err
}
opts.Id = bytes
return nil
}
}
func ResponseNumericId(id int) ResponseOption {
return func(opts *ResponseOptions) error {
bytes, err := json.Marshal(id)
if err != nil {
return err
}
opts.Id = bytes
return nil
}
}
func ResponseVersion(version string) ResponseOption {
return func(opts *ResponseOptions) error {
opts.Version = version
return nil
}
}
type ResponseOption = func(opts *ResponseOptions) error
type ResponseOptions struct {
Id json.RawMessage
Version string
}
func DefaultResponseOptions() ResponseOptions {
return ResponseOptions{
Version: "2.0",
}
}
func NewResponse(result any, options ...ResponseOption) (*Response, error) {
opts := DefaultResponseOptions()
for _, opt := range options {
if err := opt(&opts); err != nil {
return nil, err
}
}
resultBytes, err := json.Marshal(result)
if err != nil {
return nil, errors.Annotate(err, "failed to marshal result to json")
}
return &Response{Id: opts.Id, Result: resultBytes, Error: nil, Version: opts.Version}, nil
}
func NewResponseError(error Error, options ...ResponseOption) (*Response, error) {
opts := DefaultResponseOptions()
for _, opt := range options {
if err := opt(&opts); err != nil {
return nil, err
}
}
return &Response{Id: opts.Id, Result: nil, Error: &error, Version: opts.Version}, nil
}
type Response struct {
Id json.RawMessage `json:"id,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
Version string `json:"jsonrpc"`
}
func (r *Response) UnmarshalId(payload any) error {
return json.Unmarshal(r.Id, &payload)
}
func (r *Response) UnmarshalResult(payload any) error {
if r.Error != nil {
return r.Error
}
return json.Unmarshal(r.Result, &payload)
}