-
Notifications
You must be signed in to change notification settings - Fork 14
/
client.go
91 lines (79 loc) · 1.75 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
83
84
85
86
87
88
89
90
91
// tokucore
//
// Copyright 2019 by KeyFuse Labs
// BSD License
package xrpc
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"time"
)
// Request -- request for RPC.
type Request struct {
Method string `json:"method"`
Params []interface{} `json:"params"`
ID uint64 `json:"id"`
}
// Error --
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
}
// Response -- response for RPC.
type Response struct {
ID uint64 `json:"id"`
Result *json.RawMessage `json:"result"`
Error *Error `json:"error"`
}
// Client -- RPC client.
type Client struct {
rpcHost string
rpcUser string
rpcPass string
httpClient *http.Client
}
// NewClient -- creates Client.
func NewClient(host string, user string, pass string) *Client {
return &Client{
rpcHost: host,
rpcUser: user,
rpcPass: pass,
httpClient: &http.Client{},
}
}
func (c *Client) call(method string, params ...interface{}) (*Response, error) {
url := fmt.Sprintf("http://%v/", c.rpcHost)
param := &Request{
Method: method,
Params: params,
}
enc, err := json.Marshal(param)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", url, bytes.NewReader(enc))
if err != nil {
return nil, err
}
req.SetBasicAuth(c.rpcUser, c.rpcPass)
// 5s timeout.
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5)*time.Second)
req = req.WithContext(ctx)
defer cancel()
rawResp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
defer rawResp.Body.Close()
resp := &Response{}
if err := json.NewDecoder(rawResp.Body).Decode(resp); err != nil {
return nil, err
}
if resp.Error != nil {
return nil, fmt.Errorf("%v", resp.Error)
}
return resp, nil
}