/
client.go
276 lines (219 loc) · 6.56 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Package httputil provides abstractions around the common needs of HTTP. It
// also allows swapping in and out the HTTP client.
package httputil
import (
"bytes"
"context"
"io"
"mime/multipart"
"time"
"github.com/pkg/errors"
"github.com/diamondburned/arikawa/v2/utils/httputil/httpdriver"
"github.com/diamondburned/arikawa/v2/utils/json"
)
// StatusTooManyRequests is the HTTP status code discord sends on rate-limiting.
const StatusTooManyRequests = 429
// Retries is the default attempts to retry if the API returns an error before
// giving up. If the value is smaller than 1, then requests will retry forever.
var Retries uint = 5
type Client struct {
httpdriver.Client
SchemaEncoder
// OnRequest, if not nil, will be copied and prefixed on each Request.
OnRequest []RequestOption
// OnResponse is called after every Do() call. Response might be nil if Do()
// errors out. The error returned will override Do's if it's not nil.
OnResponse []ResponseFunc
// Timeout is the maximum amount of time the client will wait for a request
// to finish. If this is 0 or smaller the Client won't time out. Otherwise,
// the timeout will be used as deadline for context of every request.
Timeout time.Duration
// Default to the global Retries variable (5).
Retries uint
context context.Context
}
func NewClient() *Client {
return &Client{
Client: httpdriver.NewClient(),
SchemaEncoder: &DefaultSchema{},
Retries: Retries,
context: context.Background(),
}
}
// Copy returns a shallow copy of the client.
func (c *Client) Copy() *Client {
cl := new(Client)
*cl = *c
return cl
}
// WithContext returns a client copy of the client with the given context.
func (c *Client) WithContext(ctx context.Context) *Client {
c = c.Copy()
c.context = ctx
return c
}
// Context is a shared context for all future calls. It's Background by
// default.
func (c *Client) Context() context.Context {
return c.context
}
// applyOptions tries to apply all options. It does not halt if a single option
// fails, and the error returned is the latest error.
func (c *Client) applyOptions(r httpdriver.Request, extra []RequestOption) (e error) {
for _, opt := range c.OnRequest {
if err := opt(r); err != nil {
e = err
}
}
for _, opt := range extra {
if err := opt(r); err != nil {
e = err
}
}
return
}
// MultipartWriter is the interface for a data structure that can write into a
// multipart writer.
type MultipartWriter interface {
WriteMultipart(body *multipart.Writer) error
}
// MeanwhileMultipart concurrently encodes and writes the given multipart writer
// at the same time. The writer will be called in another goroutine, but the
// writer will be closed when MeanwhileMultipart returns.
func (c *Client) MeanwhileMultipart(
writer MultipartWriter,
method, url string, opts ...RequestOption) (httpdriver.Response, error) {
r, w := io.Pipe()
body := multipart.NewWriter(w)
// Ensure the writer is closed by the time this function exits, so
// WriteMultipart will exit.
defer w.Close()
go func() {
err := writer.WriteMultipart(body)
body.Close()
w.CloseWithError(err)
}()
// Prepend the multipart writer and the correct Content-Type header options.
opts = PrependOptions(
opts,
WithBody(r),
WithContentType(body.FormDataContentType()),
)
// Request with the current client and our own context:
return c.Request(method, url, opts...)
}
// FastRequest performs a request without waiting for the body.
func (c *Client) FastRequest(method, url string, opts ...RequestOption) error {
r, err := c.Request(method, url, opts...)
if err != nil {
return err
}
return r.GetBody().Close()
}
// RequestJSON performs a request and unmarshals the JSON body into "to".
func (c *Client) RequestJSON(to interface{}, method, url string, opts ...RequestOption) error {
opts = PrependOptions(opts, JSONRequest)
r, err := c.Request(method, url, opts...)
if err != nil {
return err
}
var body, status = r.GetBody(), r.GetStatus()
defer body.Close()
// No content, working as intended (tm)
if status == httpdriver.NoContent {
return nil
}
// to is nil for some reason. Ignore.
if to == nil {
return nil
}
if err := json.DecodeStream(body, to); err != nil {
return JSONError{err}
}
return nil
}
// Request performs a request and returns a response with an unread body. The
// caller must close it manually.
func (c *Client) Request(method, url string, opts ...RequestOption) (httpdriver.Response, error) {
response, cancel, err := c.request(method, url, opts)
if err != nil {
if cancel != nil {
cancel()
}
return nil, err
}
if cancel != nil {
return wrapCancelableResponse(response, cancel), nil
}
return response, nil
}
func (c *Client) request(
method, url string,
opts []RequestOption) (r httpdriver.Response, cancel context.CancelFunc, doErr error) {
// Error that represents the latest error in the chain.
var onRespErr error
var status int
ctx := c.context
if c.Timeout > 0 {
ctx, cancel = context.WithTimeout(ctx, c.Timeout)
}
// The c.Retries < 1 check ensures that we retry forever if that field is
// less than 1.
for i := uint(0); c.Retries < 1 || i < c.Retries; i++ {
q, err := c.Client.NewRequest(ctx, method, url)
if err != nil {
doErr = RequestError{err}
return
}
if err := c.applyOptions(q, opts); err != nil {
// We failed to apply an option, so we should call all OnResponse
// handler to clean everything up.
for _, fn := range c.OnResponse {
fn(q, nil)
}
doErr = errors.Wrap(err, "failed to apply http request options")
return
}
r, doErr = c.Client.Do(q)
// Call OnResponse() even if the request failed.
for _, fn := range c.OnResponse {
// Be sure to call ALL OnResponse handlers.
if err := fn(q, r); err != nil {
onRespErr = err
}
}
if onRespErr != nil || doErr != nil {
continue
}
if status = r.GetStatus(); status == StatusTooManyRequests || status >= 500 {
continue
}
break
}
if onRespErr != nil {
doErr = errors.Wrap(onRespErr, "OnResponse handler failed")
return
}
// If all retries failed, then wrap and return.
if doErr != nil {
doErr = RequestError{doErr}
return
}
// Response received, but with a failure status code:
if status < 200 || status > 299 {
// Try and parse the body.
var body = r.GetBody()
defer body.Close()
// This rarely happens, so we can (probably) make an exception for it.
buf := bytes.Buffer{}
buf.ReadFrom(body)
httpErr := &HTTPError{
Status: status,
Body: buf.Bytes(),
}
// Optionally unmarshal the error.
json.Unmarshal(httpErr.Body, &httpErr)
doErr = httpErr
}
return
}