-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathclient.go
259 lines (228 loc) · 5.89 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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
// SPDX-License-Identifier: Apache-2.0
//
// Copyright © 2022 The Cardano Community Authors
package koios
import (
"context"
"crypto/tls"
"fmt"
"io"
"net/http"
"net/http/httptrace"
"net/url"
"strings"
"time"
"golang.org/x/time/rate"
)
type (
// Client is api client instance.
Client struct {
r *rate.Limiter
reqStatsEnabled bool
url *url.URL
client *http.Client
commonHeaders http.Header
locked bool
auth *AuthInfo
}
)
// WithOptions returns new light clone of client with modified options applied.
func (c *Client) WithOptions(opts ...Option) (*Client, error) {
nc := &Client{
r: c.r,
reqStatsEnabled: c.reqStatsEnabled,
commonHeaders: c.commonHeaders.Clone(),
}
u, uerr := url.Parse(c.url.String())
nc.url = u
if nc.client == nil {
nc.client = c.client
}
// Apply provided options
for _, opt := range opts {
if err := opt.apply(nc); err != nil {
return nil, err
}
}
nc.locked = true
return nc, uerr
}
// HEAD sends api http HEAD request to provided relative path with query params
// and returns an HTTP response.
func (c *Client) HEAD(
ctx context.Context,
path string,
opts *RequestOptions,
) (*http.Response, error) {
return c.request(ctx, nil, "HEAD", path, nil, opts)
}
// POST sends api http POST request to provided relative path with query params
// and returns an HTTP response. When using POST method you are expected
// to handle the response according to net/http.Do documentation.
// e.g. Caller should close resp.Body when done reading from it.
func (c *Client) POST(
ctx context.Context,
path string,
body io.Reader,
opts *RequestOptions,
) (*http.Response, error) {
return c.request(ctx, nil, "POST", path, body, opts)
}
// GET sends api http GET request to provided relative path with query params
// and returns an HTTP response. When using GET method you are expected
// to handle the response according to net/http.Do documentation.
// e.g. Caller should close resp.Body when done reading from it.
func (c *Client) GET(
ctx context.Context,
path string,
opts *RequestOptions,
) (*http.Response, error) {
return c.request(ctx, nil, "GET", path, nil, opts)
}
// BaseURL returns currently used base url e.g. https://api.koios.rest/api/v0
func (c *Client) BaseURL() string {
return c.url.String()
}
// ServerURL returns currently used server url e.g. https://api.koios.rest/
func (c *Client) ServerURL() *url.URL {
return c.url.ResolveReference(&url.URL{Path: "/"})
}
func (c *Client) NewRequestOptions() *RequestOptions {
return &RequestOptions{
pageSize: PageSize,
page: 1,
query: url.Values{},
headers: c.commonHeaders.Clone(),
}
}
func (c *Client) request(
ctx context.Context,
res *Response,
method string,
path string,
body io.Reader,
opts *RequestOptions,
) (*http.Response, error) {
if opts == nil {
opts = c.NewRequestOptions()
}
if err := opts.lock(); err != nil {
return nil, err
}
path = strings.TrimLeft(path, "/")
requrl := c.url.ResolveReference(&url.URL{Path: path, RawQuery: opts.query.Encode()}).String()
if res != nil {
res.RequestURL = requrl
res.RequestMethod = method
}
req, err := http.NewRequestWithContext(ctx, strings.ToUpper(method), requrl, body)
if err != nil {
if res != nil {
res.applyError(nil, err)
}
return nil, err
}
// handle rate limit
if err := c.r.Wait(ctx); err != nil {
return nil, err
}
if auth := c.getAuth(); auth.token != "" {
opts.HeaderAdd("Authorization", "Bearer "+auth.token)
}
c.applyReqHeaders(req, opts.headers)
var (
eqerr error
rsp *http.Response
)
if res != nil && c.reqStatsEnabled {
rsp, eqerr = c.requestWithStats(req, res, opts.requestsToday)
} else {
rsp, eqerr = c.client.Do(req)
}
if ctx.Err() != nil {
return nil, ctx.Err()
}
if eqerr != nil {
if res != nil {
res.applyError(nil, eqerr)
}
return nil, eqerr
}
if res != nil {
res.applyRsp(rsp)
}
if rsp.StatusCode > http.StatusAccepted {
rerr := fmt.Errorf("%w: %s", ErrResponse, rsp.Status)
if res != nil {
res.applyError(nil, rerr)
}
return rsp, rerr
}
return rsp, nil
}
func (c *Client) applyReqHeaders(req *http.Request, headers http.Header) {
for name, values := range headers {
for _, value := range values {
req.Header.Add(name, value)
}
}
if req.Method == "POST" && len(headers.Get("Content-Type")) == 0 {
req.Header.Set("Content-Type", "application/json")
}
}
func (c *Client) requestWithStats(req *http.Request, res *Response, requestsToday uint) (*http.Response, error) {
res.Stats = &RequestStats{
Auth: c.getAuth(),
RequstesToday: requestsToday,
}
var dns, tlshs, connect time.Time
req = req.WithContext(
httptrace.WithClientTrace(
req.Context(),
&httptrace.ClientTrace{
DNSStart: func(dsi httptrace.DNSStartInfo) {
dns = time.Now().UTC()
},
DNSDone: func(ddi httptrace.DNSDoneInfo) {
res.Stats.DNSLookupDur = time.Since(dns)
},
TLSHandshakeStart: func() {
tlshs = time.Now().UTC()
},
TLSHandshakeDone: func(cs tls.ConnectionState, err error) {
res.Stats.TLSHSDur = time.Since(tlshs)
},
ConnectStart: func(network, addr string) {
connect = time.Now().UTC()
},
ConnectDone: func(network, addr string, err error) {
res.Stats.ESTCXNDur = time.Since(connect)
},
GotFirstResponseByte: func() {
res.Stats.TTFB = time.Since(res.Stats.ReqStartedAt)
},
},
),
)
res.Stats.ReqStartedAt = time.Now().UTC()
rsp, err := c.client.Transport.RoundTrip(req)
if err != nil {
res.applyError(nil, err)
return nil, err
}
res.applyRsp(rsp)
return rsp, nil
}
func (c *Client) setBaseURL(schema, host, version string, port uint16) error {
raw := fmt.Sprintf("%s://%s", schema, host)
if port != 80 && port != 443 {
raw = fmt.Sprintf("%s:%d", raw, port)
}
raw += "/api/" + version + "/"
u, err := url.ParseRequestURI(raw)
if err != nil {
return err
}
c.url = u
return nil
}