-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestor.go
320 lines (262 loc) · 10.5 KB
/
requestor.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
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
// Package requestor contains the methods to make HTTP requests to different endpoints
package requestor
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"net/http"
"net/url"
"strings"
"time"
)
// Client here is a struct that holds different configurations to tune Requestor
type Client struct {
// MaxRetriesOnError specifies how many times we should retry when a request to server fails
MaxRetriesOnError uint8
// TimeBetweenRetries specifies the amount of time between each retry
TimeBetweenRetries int64
// Timeout specifies a time limit for requests made by this
// Client. The timeout includes connection time, any
// redirects, and reading the response body. The timer remains
// running after Get, Head, Post, or Do return and will
// interrupt reading of the Response.Body.
//
// A Timeout of zero means no timeout.
// The Client cancels requests to the underlying Transport
// as if the Request's Context ended.
Timeout time.Duration
// IdleConnectionTimeout specifies how long an idle connection is kept in the connection pool
// 0 means no timeout
IdleConnectionTimeout time.Duration
// MaxConnectionsPerHost specifies the max number of connection per host which include connections in dialing
// active and idle states. When exceeded request gets cancelled with net/http: request canceled.
// 0 means no limit
MaxConnectionsPerHost int
// MaxIdleConnectionsPerHost specifies the max number of keep-alive connections per host
MaxIdleConnectionsPerHost int
// MaxIdleConnections specifies the max number of keep-alive connections
MaxIdleConnections int
// DisableKeepAlives makes sure that the transport is used only once by disabling keep-alives
// Default is true
DisableKeepAlives bool
// TLSClientConfig specifies the TLS config to use
TLSClientConfig *tls.Config
transport *http.Transport
httpClient *http.Client
}
// New creates a new Client object
func New() (client *Client) {
httpClient := &http.Client{}
return &Client{
httpClient: httpClient,
Timeout: 0,
DisableKeepAlives: true,
IdleConnectionTimeout: 0,
transport: &http.Transport{},
MaxRetriesOnError: 1,
}
}
// SetTLSClientConfig attaches custom client tls config to Transport
func (c *Client) SetTLSClientConfig(tlsConfig *tls.Config) {
c.TLSClientConfig = tlsConfig
}
// DisableKeepAlive sets keep-alive to either true/false
func (c *Client) DisableKeepAlive(val bool) {
c.DisableKeepAlives = val
}
// SetMaxConnectionsPerHost sets the max connections per host
func (c *Client) SetMaxConnectionsPerHost(connectionCount int) {
c.MaxConnectionsPerHost = connectionCount
}
// SetMaxIdleConnectionsPerHost sets the max idle connections per host
func (c *Client) SetMaxIdleConnectionsPerHost(connectionCount int) {
c.MaxIdleConnectionsPerHost = connectionCount
}
// SetMaxIdleConnections sets the max idle connections
func (c *Client) SetMaxIdleConnections(connectionCount int) {
c.MaxIdleConnections = connectionCount
}
// SetMaxRetries sets the max amount of retries and the time between them in seconds
func (c *Client) SetMaxRetries(retries uint8, timeBetweenRetries int64) {
c.MaxRetriesOnError = retries
if timeBetweenRetries == 0 {
c.TimeBetweenRetries = 1
} else {
c.TimeBetweenRetries = timeBetweenRetries
}
}
// SetTimeout sets timeout to request
func (c *Client) SetTimeout(timeout time.Duration) {
c.Timeout = timeout
}
// SetIdleConnectionTimeout sets the idle connection timeout
func (c *Client) SetIdleConnectionTimeout(timeout time.Duration) {
c.IdleConnectionTimeout = timeout
}
// Get performs a HTTP GET request. It takes in a URL, user specified headers, query params and returns Response and
// error if exist
func (c *Client) Get(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodGet, headers, queryParams, nil)
}
// Head performs a HTTP HEAD request. It takes in a URL, user specified headers, query params and returns Response and
// error if exist
func (c *Client) Head(url string) (response *http.Response, err error) {
return http.Head(url)
}
// Post performs a HTTP POST request. It takes in a URL, user specified headers, query params, data and returns
// Response and error if exist
func (c *Client) Post(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodPost, headers, queryParams, data)
}
// Put performs a HTTP PUT request. It takes in a URL, user specified headers, query params, data and returns
// Response and error if exist
func (c *Client) Put(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodPut, headers, queryParams, data)
}
// Patch performs a HTTP PATCH request. It takes in a URL, user specified headers, query params, data and returns
// Response and error if exist
func (c *Client) Patch(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodPatch, headers, queryParams, data)
}
// Delete performs a HTTP DELETE request. It takes in a URL, user specified headers, query params, data and returns
// Response and error if exist
func (c *Client) Delete(url string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodDelete, headers, queryParams, data)
}
// Connect performs a HTTP CONNECT request. It takes in a URL, user specified headers, query params and returns
// Response error if exist
func (c *Client) Connect(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodConnect, headers, queryParams, nil)
}
// Options performs a HTTP Options request. It takes in a URL, user specified headers, query params and returns
// Response and error if exist
func (c *Client) Options(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodOptions, headers, queryParams, nil)
}
// Trace performs a HTTP TRACE request. It takes in a URL, user specified headers, query params and returns Response
// and error if exist
func (c *Client) Trace(url string, headers, queryParams map[string][]string) (response *http.Response, err error) {
return c.makeRequest(url, http.MethodTrace, headers, queryParams, nil)
}
// makeRequest is a helper method for the above HTTP methods
func (c *Client) makeRequest(url, method string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
c.populateTransport()
// Converting headers to canonical headers
canonicalHeaders := make(map[string][]string, len(headers))
for headerKey, headerValue := range headers {
canonicalHeaders[http.CanonicalHeaderKey(headerKey)] = headerValue
}
contentType, ok := canonicalHeaders["Content-Type"]
for retry := 0; retry < int(c.MaxRetriesOnError); retry++ {
if ok && len(contentType) >= 1 {
if contentType[0] == "application/json" || strings.Contains(contentType[0], "application/json") {
response, err = c.makeJSONRequest(url, method, headers, queryParams, data)
if err != nil {
time.Sleep(time.Duration(c.TimeBetweenRetries) * time.Second)
continue
}
break
}
if contentType[0] == "application/x-www-form-urlencoded" || strings.Contains(contentType[0], "application/x-www-form-urlencoded") {
response, err = c.makeFormURLEncodedRequest(url, method, headers, queryParams, data)
if err != nil {
time.Sleep(time.Duration(c.TimeBetweenRetries) * time.Second)
continue
}
break
}
}
response, err = c.makeJSONRequest(url, method, headers, queryParams, data)
if err != nil {
time.Sleep(time.Duration(c.TimeBetweenRetries) * time.Second)
continue
}
break
}
if err != nil {
return response, err
}
if response == nil {
return response, errors.New("no response after retries")
}
return response, nil
}
func (c *Client) makeFormURLEncodedRequest(formURL, method string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
dataMap, ok := data.(map[string][]string)
if !ok && data != nil {
return response, errors.New("data should be of the form map[string][]string")
}
formData := url.Values{}
for formDataKey, formDataValues := range dataMap {
for _, formDataValue := range formDataValues {
formData.Add(formDataKey, formDataValue)
}
}
c.httpClient.Timeout = c.Timeout
var request *http.Request
if len(dataMap) > 0 {
request, err = http.NewRequest(method, formURL, strings.NewReader(formData.Encode()))
} else {
request, err = http.NewRequest(method, formURL, nil)
}
if err != nil {
return response, err
}
q := request.URL.Query()
for queryKey, queryValues := range queryParams {
for _, val := range queryValues {
q.Add(queryKey, val)
}
}
request.URL.RawQuery = q.Encode()
for headerKey, headerValues := range headers {
for _, val := range headerValues {
request.Header.Add(headerKey, val)
}
}
return c.httpClient.Do(request)
}
func (c *Client) makeJSONRequest(url, method string, headers, queryParams map[string][]string, data interface{}) (response *http.Response, err error) {
var dataBytes []byte
if data != nil {
dataBytes, err = json.Marshal(data)
if err != nil {
return response, err
}
}
c.httpClient.Timeout = c.Timeout
var request *http.Request
if len(dataBytes) > 0 {
request, err = http.NewRequest(method, url, bytes.NewBuffer(dataBytes))
} else {
request, err = http.NewRequest(method, url, nil)
}
if err != nil {
return response, err
}
q := request.URL.Query()
for queryKey, queryValues := range queryParams {
for _, val := range queryValues {
q.Add(queryKey, val)
}
}
request.URL.RawQuery = q.Encode()
for headerKey, headerValues := range headers {
for _, val := range headerValues {
request.Header.Add(headerKey, val)
}
}
return c.httpClient.Do(request)
}
// populateTransport populates the transport config
func (c *Client) populateTransport() {
c.transport.DisableKeepAlives = c.DisableKeepAlives
c.transport.MaxConnsPerHost = c.MaxConnectionsPerHost
c.transport.IdleConnTimeout = c.IdleConnectionTimeout
c.transport.MaxConnsPerHost = c.MaxConnectionsPerHost
c.transport.MaxIdleConnsPerHost = c.MaxIdleConnectionsPerHost
c.transport.MaxIdleConns = c.MaxIdleConnections
c.transport.TLSClientConfig = c.TLSClientConfig
c.httpClient.Transport = c.transport
}