-
Notifications
You must be signed in to change notification settings - Fork 33
/
response.go
67 lines (55 loc) · 1.28 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
package jsonrpc
import (
"encoding/json"
)
var (
jsonNull = json.RawMessage("null")
)
type Response struct {
JSONRPC string `json:"jsonrpc"`
ID ID `json:"id"`
Result interface{} `json:"result,omitempty"`
Error interface{} `json:"error,omitempty"`
}
type BatchResponse []*Response
func NewResponse() *Response {
return &Response{}
}
// MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0"
// property.
func (r Response) MarshalJSON() ([]byte, error) {
if r.Error != nil {
response := struct {
JSONRPC string `json:"jsonrpc"`
ID ID `json:"id"`
Error interface{} `json:"error,omitempty"`
}{
JSONRPC: "2.0",
ID: r.ID,
Error: r.Error,
}
return json.Marshal(response)
} else {
response := struct {
JSONRPC string `json:"jsonrpc"`
ID ID `json:"id"`
Result interface{} `json:"result,omitempty"`
}{
JSONRPC: "2.0",
ID: r.ID,
Result: r.Result,
}
if response.Result == nil {
response.Result = jsonNull
}
return json.Marshal(response)
}
}
// UnmarshalJSON implements json.Unmarshaler.
func (r *Response) UnmarshalJSON(data []byte) error {
type tmpType Response
if err := json.Unmarshal(data, (*tmpType)(r)); err != nil {
return err
}
return nil
}