-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
99 lines (82 loc) · 1.91 KB
/
request.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
94
95
96
97
98
99
package jsonrpc
import (
"encoding/json"
"github.com/juju/errors"
)
func RequestVersion(version string) RequestOption {
return func(opts *RequestOptions) error {
opts.Version = version
return nil
}
}
func RequestStringId(id string) RequestOption {
return func(opts *RequestOptions) error {
bytes, err := json.Marshal(id)
if err != nil {
return err
}
opts.Id = bytes
return nil
}
}
func RequestNumericId(id int) RequestOption {
return func(opts *RequestOptions) error {
bytes, err := json.Marshal(id)
if err != nil {
return err
}
opts.Id = bytes
return nil
}
}
type RequestOption = func(opts *RequestOptions) error
type RequestOptions struct {
Version string
Id json.RawMessage
}
func DefaultRequestOptions() RequestOptions {
return RequestOptions{
Version: "2.0",
}
}
func NewRequest(method string, params any, options ...RequestOption) (*Request, error) {
opts := DefaultRequestOptions()
for _, opt := range options {
if err := opt(&opts); err != nil {
return nil, err
}
}
var err error
var paramBytes json.RawMessage
if params != nil {
paramBytes, err = json.Marshal(params)
if err != nil {
return nil, errors.New("failed to marshal params to json")
}
}
return &Request{Id: opts.Id, Method: method, Params: paramBytes, Version: opts.Version}, nil
}
type IdGenerator = func() string
type Request struct {
Id json.RawMessage `json:"id,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
Version string `json:"jsonrpc,omitempty"`
}
func (r *Request) EnsureId(gen IdGenerator) error {
if r.Id != nil {
return nil
}
bytes, err := json.Marshal(gen())
if err != nil {
return err
}
r.Id = bytes
return nil
}
func (r *Request) UnmarshalId(id any) error {
return json.Unmarshal(r.Id, &id)
}
func (r *Request) UnmarshalParams(payload any) error {
return json.Unmarshal(r.Params, &payload)
}