-
Notifications
You must be signed in to change notification settings - Fork 17
/
response.go
56 lines (48 loc) · 1.69 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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
package jsonrpc
import (
"encoding/json"
"fmt"
)
// ResponseError is type of JSON-RPC response error, it implements error interface.
type ResponseError struct {
Code int32 `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
// Error implements error interface, returns `Code` + `Message`
func (e *ResponseError) Error() string {
return fmt.Sprintf("%d - %s", e.Code, e.Message)
}
// Response is type of JSON-RPC response struct
type Response struct {
JsonRpc string `json:"jsonrpc"`
ID *RequestID `json:"id"`
Result *json.RawMessage `json:"result"`
Error *ResponseError `json:"error"`
DiemChainID byte `json:"diem_chain_id"`
DiemLedgerTimestampusec uint64 `json:"diem_ledger_timestampusec"`
DiemLedgerVersion uint64 `json:"diem_ledger_version"`
}
// UnmarshalResult unmarshals result json into given struct.
// Returns true, nil for success unmarshal, otherwise first bool
// will always be false.
// Returns false, nil if `Result` is nil.
func (r *Response) UnmarshalResult(result interface{}) (bool, error) {
if r.Result == nil {
return false, nil
}
if err := json.Unmarshal(*r.Result, result); err != nil {
return false, newError(ParseResponseResultJsonError, err)
}
return true, nil
}
// Validate validates response data with JSON-RPC 2.0 spec
func (r *Response) Validate() error {
if r.JsonRpc != "2.0" {
return newError(InvalidJsonRpcResponseError,
fmt.Errorf("unexpected jsonrpc version: %s", r.JsonRpc))
}
return nil
}