-
Notifications
You must be signed in to change notification settings - Fork 5
/
client.go
249 lines (209 loc) · 5.93 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
package clink
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"golang.org/x/time/rate"
)
// Client is a wrapper around http.Client with additional functionality.
type Client struct {
HttpClient *http.Client
Headers map[string]string
RateLimiter *rate.Limiter
MaxRetries int
ShouldRetryFunc func(*http.Request, *http.Response, error) bool
}
// NewClient creates a new client with the given options.
func NewClient(opts ...Option) *Client {
c := defaultClient()
for _, opt := range opts {
opt(c)
}
return c
}
func defaultClient() *Client {
return &Client{
HttpClient: http.DefaultClient,
Headers: make(map[string]string),
}
}
// Do sends the given request and returns the response.
// If the request is rate limited, the client will wait for the rate limiter to allow the request.
// If the request fails, the client will retry the request the number of times specified by MaxRetries.
func (c *Client) Do(req *http.Request) (*http.Response, error) {
for key, value := range c.Headers {
req.Header.Set(key, value)
}
if c.RateLimiter != nil {
if err := c.RateLimiter.Wait(req.Context()); err != nil {
return nil, fmt.Errorf("failed to wait for rate limiter: %w", err)
}
}
var resp *http.Response
var body []byte
var err error
if req.Body != nil && req.Body != http.NoBody {
body, err = io.ReadAll(req.Body)
if err != nil {
return nil, fmt.Errorf("failed to read request body: %w", err)
}
err = req.Body.Close()
if err != nil {
return nil, fmt.Errorf("failed to close request body: %w", err)
}
}
for attempt := 0; attempt <= c.MaxRetries; attempt++ {
if len(body) > 0 {
req.Body = io.NopCloser(bytes.NewReader(body))
}
resp, err = c.HttpClient.Do(req)
if req.Context().Err() != nil {
return nil, fmt.Errorf("request context error: %w", req.Context().Err())
}
if c.ShouldRetryFunc != nil && !c.ShouldRetryFunc(req, resp, err) {
break
}
if attempt < c.MaxRetries {
select {
case <-time.After(time.Duration(attempt) * time.Second):
case <-req.Context().Done():
return nil, req.Context().Err()
}
}
}
if err != nil {
return nil, fmt.Errorf("failed to do request: %w", err)
}
return resp, nil
}
// Head sends a HEAD request to the given URL.
func (c *Client) Head(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodHead, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Get sends a GET request to the given URL.
func (c *Client) Options(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodOptions, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Get sends a GET request to the given URL.
func (c *Client) Get(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Post sends a POST request to the given URL with the given body.
func (c *Client) Post(url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPost, url, body)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Put sends a PUT request to the given URL.
func (c *Client) Put(url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPut, url, body)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Patch sends a PATCH request to the given URL.
func (c *Client) Patch(url string, body io.Reader) (*http.Response, error) {
req, err := http.NewRequest(http.MethodPatch, url, body)
if err != nil {
return nil, err
}
return c.Do(req)
}
// Delete sends a DELETE request to the given URL.
func (c *Client) Delete(url string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodDelete, url, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
type Option func(*Client)
// WithClient sets the http client for the client.
func WithClient(client *http.Client) Option {
return func(c *Client) {
c.HttpClient = client
}
}
// WithHeader sets a header for the client.
func WithHeader(key, value string) Option {
return func(c *Client) {
c.Headers[key] = value
}
}
// WithHeaders sets the headers for the client.
func WithHeaders(headers map[string]string) Option {
return func(c *Client) {
for key, value := range headers {
c.Headers[key] = value
}
}
}
// WithRateLimit sets the rate limit for the client in requests per minute.
func WithRateLimit(rpm int) Option {
return func(c *Client) {
interval := time.Minute / time.Duration(rpm)
c.RateLimiter = rate.NewLimiter(rate.Every(interval), 1)
}
}
// WithBasicAuth sets the basic auth header for the client.
func WithBasicAuth(username, password string) Option {
return func(c *Client) {
auth := username + ":" + password
encodedAuth := base64.StdEncoding.EncodeToString([]byte(auth))
c.Headers["Authorization"] = "Basic " + encodedAuth
}
}
// WithBearerAuth sets the bearer auth header for the client.
func WithBearerAuth(token string) Option {
return func(c *Client) {
c.Headers["Authorization"] = "Bearer " + token
}
}
// WithUserAgent sets the user agent header for the client.
func WithUserAgent(ua string) Option {
return func(c *Client) {
c.Headers["User-Agent"] = ua
}
}
// WithRetries sets the retry count and retry function for the client.
func WithRetries(count int, retryFunc func(*http.Request, *http.Response, error) bool) Option {
return func(c *Client) {
c.MaxRetries = count
c.ShouldRetryFunc = retryFunc
}
}
// ResponseToJson decodes the response body into the target.
func ResponseToJson[T any](response *http.Response, target *T) error {
if response == nil {
return fmt.Errorf("response is nil")
}
if response.Body == nil {
return fmt.Errorf("response body is nil")
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(response.Body)
if err := json.NewDecoder(response.Body).Decode(target); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
return nil
}