forked from danikarik/ncanode-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
122 lines (101 loc) · 2.32 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package ncanode
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"time"
)
const _timeout = 60 * time.Second
// Option changes client properties.
type Option func(c *Client) error
// WithTimeout sets http client timeout by given duration.
func WithTimeout(t time.Duration) Option {
return func(c *Client) error {
c.client.Timeout = t
return nil
}
}
// WithHTTPClient sets own http client.
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) error {
c.client = hc
return nil
}
}
// Client is API client.
type Client struct {
host string
version string
client *http.Client
}
// NewClient returns a new Client.
//
// Takes NCANode host address and options.
func NewClient(addr string, opts ...Option) (*Client, error) {
if addr == "" {
return nil, errors.New("ncanode: address invalid or empty")
}
client := &Client{
host: addr,
version: "1.0",
client: &http.Client{Timeout: _timeout},
}
for _, opt := range opts {
if err := opt(client); err != nil {
return nil, err
}
}
if err := client.ping(); err != nil {
return nil, err
}
return client, nil
}
type modifier func(data []byte) ([]byte, error)
func (c *Client) call(body, reply interface{}, mods ...modifier) error {
buf, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("encode payload: %w", err)
}
for _, mod := range mods {
data, err := mod(buf)
if err != nil {
return fmt.Errorf("apply modifier: %w", err)
}
buf = data
}
req, err := http.NewRequest("POST", c.host, bytes.NewReader(buf))
if err != nil {
return fmt.Errorf("create request %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.client.Do(req)
if err != nil {
return fmt.Errorf("do request: %w", err)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("read request: %w", err)
}
defer resp.Body.Close()
var apiResp apiResponse
if err := json.Unmarshal(data, &apiResp); err != nil {
return fmt.Errorf("read api response: %w", err)
}
if apiResp.Status != 0 || apiResp.Message != "" {
return apiResp
}
if err := json.Unmarshal(data, &reply); err != nil {
return fmt.Errorf("decode payload: %w", err)
}
return nil
}
func (c *Client) ping() error {
_, err := c.client.Get(c.host)
if err != nil {
return ErrFailedConnection
}
return nil
}