-
Notifications
You must be signed in to change notification settings - Fork 3
/
client.go
65 lines (53 loc) · 1.2 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
package hpc
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
// Config for the RPC client.
type Config struct {
HTTPClient *http.Client // Custom HTTP client
URL string // URL end-point for RPC services
}
// Client lets you make calls to an HTTP-RPC end-point.
type Client struct {
*Config
}
// NewClient returns a new client.
func NewClient(config *Config) *Client {
return &Client{
Config: config,
}
}
// NewConfig returns configuration for the given `url`.
func NewConfig(url string) *Config {
return &Config{
URL: url,
HTTPClient: http.DefaultClient,
}
}
// Call a method.
func (c *Client) Call(service, method string, in interface{}, out interface{}) error {
url := fmt.Sprintf("%s/%s/%s", c.URL, service, method)
b, err := json.Marshal(in)
if err != nil {
return err
}
res, err := c.HTTPClient.Post(url, "application/json", bytes.NewBuffer(b))
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode >= 400 {
var e statusError
if err := json.NewDecoder(res.Body).Decode(&e); err != nil {
return &statusError{
Status: res.StatusCode,
Message: res.Status,
}
}
return &e
}
return json.NewDecoder(res.Body).Decode(out)
}