forked from kdar/httprpc
/
client.go
70 lines (62 loc) · 1.89 KB
/
client.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
// HTTP JSON Gorilla RPC for golang
package json2
import (
"encoding/json"
"fmt"
"io"
"math/rand"
"strings"
)
// clientRequest represents a JSON-RPC v2.0 request sent by a client.
type clientRequest struct {
// A String containing the name of the method to be invoked.
Method string `json:"method"`
// Object to pass as request parameter to the method.
Params interface{} `json:"params"`
// The request id. This can be of any type. It is used to match the
// response with the request that it is replying to.
Id uint64 `json:"id"`
// Always set to 2.0
Jsonrpc string `json:"jsonrpc"`
}
// clientResponse represents a JSON-RPC response returned to a client.
type clientResponse struct {
Result *json.RawMessage `json:"result"`
Error interface{} `json:"error"` // {"code": -32700, "message": "Parse error"}
Id uint64 `json:"id"`
Jsonrpc string `json:"jsonrpc"`
}
// EncodeClientRequest encodes parameters for a JSON-RPC v2.0 client request.
func EncodeClientRequest(method string, args interface{}) ([]byte, error) {
c := &clientRequest{
Method: method,
Params: args,
Id: uint64(rand.Int63()),
Jsonrpc: "2.0",
}
return json.Marshal(c)
}
type Error map[string]interface{}
func (e Error) Error() string {
var parts []string
for key, value := range e {
parts = append(parts, fmt.Sprintf("%s: %s", key, value))
}
return strings.Join(parts, ", ")
}
// DecodeClientResponse decodes the response body of a client request into
// the interface reply.
func DecodeClientResponse(r io.Reader, reply interface{}) error {
var c clientResponse
if err := json.NewDecoder(r).Decode(&c); err != nil {
return err
}
if c.Error != nil {
if eror, ok := c.Error.(map[string]interface{}); ok {
return Error(eror)
} else {
return fmt.Errorf("%v", c.Error)
}
}
return json.Unmarshal(*c.Result, reply)
}