-
Notifications
You must be signed in to change notification settings - Fork 6
/
request.go
65 lines (53 loc) · 1.59 KB
/
request.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
// Copyright 2021-present Airheart, Inc. All rights reserved.
// This source code is licensed under the Apache 2.0 license found
// in the LICENSE file in the root directory of this source tree.
package duffel
import (
"context"
"fmt"
"net/http"
"time"
"golang.org/x/time/rate"
)
func newInternalClient[Req any, Resp any](a *API) *client[Req, Resp] {
client := &client[Req, Resp]{
httpDoer: a.httpDoer,
options: a.options,
APIToken: a.APIToken,
limiter: rate.NewLimiter(rate.Every(1*time.Second), 5),
afterResponse: []func(resp *http.Response){
func(resp *http.Response) {
a.lastRequestID = resp.Header.Get(RequestIDHeader)
},
},
}
return client
}
func (c *client[Req, Resp]) Do(ctx context.Context, resourceName string, method string, body *Req, opts ...RequestOption) (*http.Response, error) {
payload, err := encodePayload(body)
if err != nil {
return nil, err
}
err = c.limiter.Wait(ctx) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
resp, err := c.makeRequest(ctx, resourceName, method, payload, opts...)
if err != nil {
return nil, err
}
for _, afterResponse := range c.afterResponse {
afterResponse(resp)
}
rateLimit, err := parseRateLimit(resp)
if err != nil {
return nil, err
}
c.rateLimit = rateLimit
c.limiter.SetBurst(rateLimit.Limit)
c.limiter.SetLimit(rate.Every(rateLimit.Period))
if rateLimit.Remaining == 0 || resp.StatusCode == http.StatusTooManyRequests {
return nil, fmt.Errorf("rate limit exceeded, reset in: %s, current limit: %d", rateLimit.Period.String(), rateLimit.Limit)
}
return resp, nil
}