-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathclient.go
171 lines (143 loc) · 3.08 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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package blockonomics
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/http/httputil"
"net/url"
"path"
"time"
)
var APIBase = "https://www.blockonomics.co"
type APIClient struct {
APIBase string
Client *http.Client
token string
timeout time.Duration
Logger io.Writer
}
func NewClient(token string, opts ...Option) *APIClient {
c := &APIClient{
APIBase: APIBase,
token: token,
Logger: NewNopLogger(),
}
for _, o := range opts {
o(c)
}
c.Client = &http.Client{
Timeout: c.timeout,
}
return c
}
type Option func(s *APIClient)
func WithTimeout(timeout time.Duration) Option {
return func(s *APIClient) {
s.timeout = timeout
}
}
func WithLogger(output io.Writer) Option {
return func(s *APIClient) {
s.Logger = output
}
}
type nopLogger struct{}
func NewNopLogger() *nopLogger { return &nopLogger{} }
func (nopLogger) Write(p []byte) (n int, err error) { return len(p), nil }
func (c *APIClient) newRequest(method, urlEndpoint string, payload interface{}) (*http.Request, error) {
u, err := url.Parse(c.APIBase)
if err != nil {
return nil, err
}
u.Path = path.Join(u.Path, urlEndpoint)
var buf io.Reader
if payload != nil {
b, err := json.Marshal(&payload)
if err != nil {
return nil, err
}
buf = bytes.NewBuffer(b)
}
return http.NewRequest(method, u.String(), buf)
}
func (c *APIClient) auth(req *http.Request) {
req.Header.Set("Authorization", "Bearer "+c.token)
}
type Error struct {
err error
}
func (e *Error) Error() string {
return "APIClient: " + e.err.Error()
}
func (e *Error) Unwrap() error {
return e.err
}
var (
ErrUnauthorised = errors.New("unauthorised")
ErrBadRequest = errors.New("bad request")
ErrServer = errors.New("server error")
ErrInternal = errors.New("internal error")
)
func (c *APIClient) send(req *http.Request, v interface{}) error {
var (
err error
resp *http.Response
)
// Set default headers
req.Header.Set("Accept", "application/json")
req.Header.Set("Accept-Language", "en_US")
// Default values for headers
if req.Header.Get("Content-type") == "" {
req.Header.Set("Content-type", "application/json")
}
resp, err = c.Client.Do(req)
if err != nil {
return err
}
if resp != nil {
defer resp.Body.Close()
}
defer func() {
c.log(req, resp)
}()
switch resp.StatusCode {
case http.StatusOK:
if v == nil {
return nil
}
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
return err
}
return json.NewDecoder(resp.Body).Decode(v)
case http.StatusUnauthorized:
return &Error{
err: ErrUnauthorised,
}
case http.StatusBadRequest:
return &Error{
err: ErrBadRequest,
}
default:
return &Error{
err: ErrServer,
}
}
}
// log will dump request and response to the log file
func (c *APIClient) log(req *http.Request, resp *http.Response) {
var reqDump, respDump []byte
if req != nil {
reqDump, _ = httputil.DumpRequest(req, true)
}
if resp != nil {
respDump, _ = httputil.DumpResponse(resp, true)
}
_, _ = c.Logger.Write([]byte(fmt.Sprintf(
"Request: %s\nResponse: %s",
string(reqDump),
string(respDump))))
}