forked from hectorchu/gonano
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
56 lines (53 loc) · 1.09 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
package rpc
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net/http"
)
// Client is used for connecting to http rpc endpoints.
type Client struct {
URL string
AuthHeader string
Ctx context.Context
}
func (c *Client) send(body interface{}) (result []byte, err error) {
var buf bytes.Buffer
if err = json.NewEncoder(&buf).Encode(body); err != nil {
return
}
if c.Ctx == nil {
c.Ctx = context.Background()
}
req, err := http.NewRequestWithContext(c.Ctx, http.MethodPost, c.URL, &buf)
if err != nil {
return
}
req.Header.Set("Content-Type", "application/json")
if c.AuthHeader != "" {
req.Header.Set("Authorization", c.AuthHeader)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return
}
buf.Reset()
if _, err = io.Copy(&buf, resp.Body); err != nil {
return
}
if err = resp.Body.Close(); err != nil {
return
}
var v struct{ Error, Message string }
if err = json.Unmarshal(buf.Bytes(), &v); err != nil {
return
}
if v.Error != "" {
err = errors.New(v.Error)
} else if v.Message != "" {
err = errors.New(v.Message)
}
return buf.Bytes(), err
}