-
Notifications
You must be signed in to change notification settings - Fork 9
/
jsonrpc2_types.go
93 lines (79 loc) · 2.29 KB
/
jsonrpc2_types.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 jsonrpc2
import (
"encoding/json"
"fmt"
"strconv"
)
// JSONRPCError : standard JSONRPC Error
type JSONRPCError struct {
Code int `json:"code"`
Message string `json:"message"`
Data string `json:"data,omitempty"`
}
// JSONRPCRequest standard JSONRPC 2 Request
type JSONRPCRequest struct {
Version string `json:"jsonrpc"`
Method string `json:"method"`
Params interface{} `json:"params"`
ID string `json:"id"`
}
// JSONRPCMessage : standard JSONRPC 2 Response
type JSONRPCMessage struct {
Version string `json:"jsonrpc"`
ID string `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Error *JSONRPCError `json:"error,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Raw json.RawMessage `json:"-"`
}
// DecodeError : error returned when failing to decode a response
type DecodeError struct {
Raw []byte
Err error
}
// Error message string
func (d DecodeError) Error() string {
return fmt.Sprintf("Error decoding %s: %s", d.Raw, d.Err)
}
func (msg *JSONRPCMessage) IsNotification() bool {
return msg.ID == "" && msg.Method != ""
}
func (msg *JSONRPCMessage) IsResponse() bool {
return msg.HasValidID() && msg.Method == "" && len(msg.Params) == 0
}
func (msg *JSONRPCMessage) HasValidID() bool {
return len(msg.ID) > 0 && msg.ID[0] != '{' && msg.ID[0] != '['
}
// ValidID decods the id if it s valid
func (msg *JSONRPCMessage) ValidID() (string, error) {
if !msg.HasValidID() {
return "", fmt.Errorf("Message does not have a valid id")
}
return string(msg.ID), nil
}
// UINTResult decods the the result as uint
func (msg *JSONRPCMessage) UINTResult() (uint64, error) {
var s string
err := json.Unmarshal(msg.Result, &s)
if err != nil {
return 0, err
}
return strconv.ParseUint(s, 0, 64)
}
func (msg *JSONRPCMessage) String() string {
b, _ := json.Marshal(msg)
return string(b)
}
// JSONRPCNotification : standard JSONRPC 2 Notification
type JSONRPCNotification struct {
ID string `json:"subscription"`
Result json.RawMessage `json:"result"`
}
// ValidID decods the id if it s valid
func (msg *JSONRPCNotification) ValidID() (string, error) {
if len(msg.ID) == 0 {
return "", fmt.Errorf("No ID found")
}
return msg.ID, nil
}