-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
82 lines (66 loc) · 1.39 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
71
72
73
74
75
76
77
78
79
80
81
82
package jsonrpc
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"strings"
"time"
)
type (
Client struct {
endpoint string
timeout uint64
resp *Response
}
)
func NewClient(endpoint string) *Client {
return &Client{
endpoint: endpoint,
timeout: 10,
}
}
func (rpc *Client) SetTimeout(sec uint64) {
rpc.timeout = sec
}
func (rpc *Client) Call(method string, params ...interface{}) (*Response, error) {
if strings.TrimSpace(method) == "" {
return nil, errors.WithStack(errors.New("Empty 'method' parameter"))
}
r := &Request{
JsonRPC: "2.0",
Method: method,
}
if len(params) == 1 {
r.Params = params[0]
}
b, err := json.Marshal(r)
if err != nil {
return nil, errors.WithStack(err)
}
req, err := http.NewRequest("POST", rpc.endpoint, bytes.NewReader(b))
if err != nil {
return nil, errors.WithStack(err)
}
rsp, err := (&http.Client{
Timeout: time.Duration(rpc.timeout) * time.Second,
}).Do(req)
if err != nil {
return nil, errors.WithStack(err)
}
body, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, errors.WithStack(err)
}
if err := rsp.Body.Close(); err != nil {
return nil, errors.WithStack(err)
}
rpc.resp = &Response{}
if err := json.Unmarshal(body, &rpc.resp); err != nil {
return nil, errors.WithStack(err)
}
return rpc.resp, nil
}
func (rpc *Client) ToObject(obj interface{}) {
}