-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
75 lines (61 loc) · 1.79 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
package jsonrpc
import (
"encoding/json"
"strconv"
"sync/atomic"
)
var id uint64
type Params struct {
Data []byte
Value interface{}
}
// MarshalJSON returns params as the JSON encoding of params.
func (params Params) MarshalJSON() ([]byte, error) {
if params.Value == nil {
return []byte("null"), nil
}
return json.Marshal(params.Value)
}
// UnmarshalJSON sets *params to a copy of data.
func (params *Params) UnmarshalJSON(data []byte) error {
params.Data = append(params.Data[0:0], data...)
return nil
}
// NewRequest creates new JSONRPC request object
func NewRequest(method string, params interface{}) Request {
return Request{
ID: strconv.AppendUint(nil, atomic.AddUint64(&id, 1), 10),
Method: method,
Version: SupportedVersion,
Params: &Params{Value: params},
}
}
// NewNotification creates new JSONRPC request object without ID
func NewNotification(method string, params interface{}) Request {
return Request{
Method: method,
Version: SupportedVersion,
Params: &Params{Value: params},
}
}
// Request JSONRPC request object representation
type Request struct {
ID json.RawMessage `json:"id,omitempty"`
Version string `json:"jsonrpc"`
Method string `json:"method"`
Params *Params `json:"params,omitempty"`
}
// Process request with method dispatcher
func (request Request) Process(dispatcher Dispatcher, responder Responder) {
if request.Version != SupportedVersion {
responder.Respond(nil, NewError(InvalidRequest, "Version '%s' Is Not Supported", request.Version))
}
if request.Method == "" {
responder.Respond(nil, NewError(InvalidRequest, "Empty Method"))
}
dispatcher.DispatchRequest(request, responder)
}
// IsNotification handles JSONRPC notification
func (request Request) IsNotification() bool {
return request.ID == nil
}