-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfetch.go
More file actions
331 lines (293 loc) · 9.76 KB
/
fetch.go
File metadata and controls
331 lines (293 loc) · 9.76 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
// Package fetch provides a simple fetch client with a built-in backup / retry strategy.
// Provides a interface for cancelable HTTP requests.
package fetch
import (
"context"
"errors"
"io"
"log"
"net/http"
"time"
)
// New initialises and returns a new Client instance with the provided options or default configurations if nil.
func New(options *Options) *Client {
if options == nil {
return setDefaultFetch()
}
// defaults
var fetch Client
fetch.DefaultHeaders = options.DefaultHeaders
fetch.Client = setDefaultClient()
if options.WithRetry {
fetch.RetryStrategy = setDefaultRetryStrategy()
}
// overrides
if options.HTTPClient != nil {
fetch.Client = options.HTTPClient
}
if options.RetryStrategy != nil {
fetch.RetryStrategy = *options.RetryStrategy
}
return &fetch
}
// Get sends an HTTP GET request to the specified URL with optional headers and returns the HTTP response or an error.
//
// Example:
//
// var apiErr *fetch.APIError
//
// resp, err := client.Get(url, nil)
// if err != nil {
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) Get(url string, headers map[string]string) (*http.Response, error) {
ctx := context.Background()
return a.do(ctx, url, http.MethodGet, nil, headers)
}
// Post sends an HTTP POST request to the specified URL with a body and optional headers, returning the HTTP response or an error.
//
// Example:
//
// var apiErr *fetch.APIError
//
// resp, err := client.Post(url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) Post(url string, body io.Reader, headers map[string]string) (*http.Response, error) {
ctx := context.Background()
return a.do(ctx, url, http.MethodPost, body, headers)
}
// Put sends an HTTP PUT request to the specified URL with a body and optional headers, returning the HTTP response or an error.
//
// Example:
//
// var apiErr *fetch.APIError
//
// resp, err := client.Put(url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) Put(url string, body io.Reader, headers map[string]string) (*http.Response, error) {
ctx := context.Background()
return a.do(ctx, url, http.MethodPut, body, headers)
}
// Delete sends an HTTP DELETE request to the specified URL with a body and optional headers, returning the response or an error.
//
// Example:
//
// var apiErr *fetch.APIError
//
// resp, err := client.Delete(url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) Delete(url string, body io.Reader, headers map[string]string) (*http.Response, error) {
ctx := context.Background()
return a.do(ctx, url, http.MethodDelete, body, headers)
}
// Patch sends an HTTP PATCH request to the specified URL with a body and optional headers, returning the response or an error.
// Example:
//
// var apiErr *fetch.APIError
//
// resp, err := client.Patch(url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) Patch(url string, body io.Reader, headers map[string]string) (*http.Response, error) {
ctx := context.Background()
return a.do(ctx, url, http.MethodPatch, body, headers)
}
// GetCtx sends a cancelable HTTP GET request to the specified URL with context and optional headers, returning the response or an error.
//
// Example:
//
// var apiErr *fetch.APIError
// ctx, cancel := context.WithCancel(context.Background())
//
// resp, err := client.GetCtx(ctx,url, nil)
// if err != nil {
// if errors.is(err, context.Canceled) {
// // Handle context cancelled
// }
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) GetCtx(ctx context.Context, url string, headers map[string]string) (*http.Response, error) {
return a.do(ctx, url, http.MethodGet, nil, headers)
}
// PostCtx sends a cancelable HTTP POST request to the specified URL with context, body, and headers, returning a response or error.
//
// Example:
//
// var apiErr *fetch.APIError
// ctx, cancel := context.WithCancel(context.Background())
//
// resp, err := client.PostCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.is(err, context.Canceled) {
// // Handle context cancelled
// }
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) PostCtx(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error) {
return a.do(ctx, url, http.MethodPost, body, headers)
}
// PutCtx sends a cancelable HTTP PUT request to the specified URL with context, body, and headers, returning a response or error.
//
// Example:
//
// var apiErr *fetch.APIError
// ctx, cancel := context.WithCancel(context.Background())
//
// resp, err := client.PutCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.is(err, context.Canceled) {
// // Handle context cancelled
// }
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) PutCtx(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error) {
return a.do(ctx, url, http.MethodPut, body, headers)
}
// DeleteCtx sends a cancelable HTTP DELETE request to the specified URL with context, body, and headers, returning a response or error.
//
// Example:
//
// var apiErr *fetch.APIError
// ctx, cancel := context.WithCancel(context.Background())
//
// resp, err := client.DeleteCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.is(err, context.Canceled) {
// // Handle context cancelled
// }
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) DeleteCtx(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error) {
return a.do(ctx, url, http.MethodDelete, body, headers)
}
// PatchCtx sends an HTTP PATCH request to the specified URL with the provided context, body, and headers.
//
// Example:
//
// var apiErr *fetch.APIError
// ctx, cancel := context.WithCancel(context.Background())
//
// resp, err := client.PatchCtx(ctx,url, bytes.NewReader([]byte(`{"hello": "world"}`)), nil)
// if err != nil {
// if errors.is(err, context.Canceled) {
// // Handle context cancelled
// }
// if errors.As(err, &apiErr) {
// fmt.Println("API Response error", apiErr)
// }
// // Handle non-API Error
// }
func (a *Client) PatchCtx(ctx context.Context, url string, body io.Reader, headers map[string]string) (*http.Response, error) {
return a.do(ctx, url, http.MethodPatch, body, headers)
}
// do - make http call with the provided configuration
func (a *Client) do(ctx context.Context, url string, method string, body io.Reader, headers map[string]string) (*http.Response, error) {
if a.RetryStrategy == nil {
return a.call(ctx, url, method, body, headers, a.DefaultHeaders)
}
return a.callWithRetry(ctx, url, method, body, headers, a.DefaultHeaders)
}
// callWithRetry - wrap the call method with the retry strategy
func (a *Client) callWithRetry(ctx context.Context, url string, method string, body io.Reader, headers ...map[string]string) (*http.Response, error) {
logPrefix := "fetch: callWithRetry"
var resp *http.Response
var err error
if len(a.RetryStrategy) == 0 {
return resp, ErrNoValidRetryStrategy
}
for _, retryWait := range a.RetryStrategy {
resp, err = a.call(ctx, url, method, body, headers...)
if err == nil || !isRecoverable(err) {
if errors.Is(err, context.Canceled) {
log.Printf("%s: http %s request canceled", logPrefix, method)
}
break
}
log.Printf("%s: http %s request error [%s], will retry in [%s]", logPrefix, method, err, retryWait)
time.Sleep(retryWait)
}
return resp, err
}
// call - creates a new HTTP request and returns an HTTP response
func (a *Client) call(ctx context.Context, url string, method string, body io.Reader, headers ...map[string]string) (*http.Response, error) {
req, err := http.NewRequestWithContext(ctx, method, url, body)
if err != nil {
return &http.Response{}, err
}
allHeaders := mergeHeaders(headers...)
for key, value := range allHeaders {
req.Header.Add(key, value)
}
log.Println("request", req == nil)
resp, err := a.Client.Do(req)
if err != nil {
return resp, err
}
if resp.StatusCode > 399 {
return resp, &APIError{
StatusCode: resp.StatusCode,
StatusText: http.StatusText(resp.StatusCode),
}
}
return resp, err
}
// mergeHeaders - merge a slice of headers
func mergeHeaders(headersList ...map[string]string) map[string]string {
mergedHeaders := map[string]string{}
for _, headers := range headersList {
for key, value := range headers {
mergedHeaders[key] = value
}
}
return mergedHeaders
}
// isRecoverable - checks if the response status code not within the 4XX range or is non standard status code
func isRecoverable(err error) bool {
var apiError *APIError
if !errors.As(err, &apiError) {
return false
}
switch {
case apiError.StatusCode == http.StatusNotImplemented:
return false
case (apiError.StatusCode >= http.StatusBadRequest && apiError.StatusCode < http.StatusInternalServerError):
return false
case apiError.StatusCode == 0, apiError.StatusCode > 599:
return false
}
return true
}