-
Notifications
You must be signed in to change notification settings - Fork 33
/
raw_response.go
60 lines (51 loc) · 1.42 KB
/
raw_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
package jsonrpc
import (
"encoding/json"
)
// RawResponse keeps Result and Error as unparsed JSON
// It is meant to be used to deserialize JSONPRC responses from downstream components
// while Response is meant to be used to craft our own responses to clients.
type RawResponse struct {
JSONRPC string `json:"jsonrpc"`
ID ID `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *json.RawMessage `json:"error,omitempty"`
}
// MarshalJSON implements json.Marshaler and adds the "jsonrpc":"2.0"
// property.
func (r RawResponse) MarshalJSON() ([]byte, error) {
if r.Error != nil {
response := struct {
JSONRPC string `json:"jsonrpc"`
ID ID `json:"id"`
Error json.RawMessage `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 json.RawMessage `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 *RawResponse) UnmarshalJSON(data []byte) error {
type tmpType RawResponse
if err := json.Unmarshal(data, (*tmpType)(r)); err != nil {
return err
}
return nil
}