-
Notifications
You must be signed in to change notification settings - Fork 146
/
httphelpers.go
431 lines (348 loc) · 9.03 KB
/
httphelpers.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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
package mailgun
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"regexp"
"strings"
"sync"
"github.com/mailgun/errors"
)
var validURL = regexp.MustCompile(`/v[1-5].*`)
type httpRequest struct {
URL string
Parameters map[string][]string
Headers map[string]string
BasicAuthUser string
BasicAuthPassword string
Client *http.Client
mu sync.RWMutex
capturedCurlOutput string
}
type httpResponse struct {
Code int
Data []byte
}
type payload interface {
getPayloadBuffer() (*bytes.Buffer, error)
getContentType() (string, error)
getValues() []keyValuePair
}
type keyValuePair struct {
key string
value string
}
type keyNameRC struct {
key string
name string
value io.ReadCloser
}
type keyNameBuff struct {
key string
name string
value []byte
}
type FormDataPayload struct {
contentType string
Values []keyValuePair
Files []keyValuePair
ReadClosers []keyNameRC
Buffers []keyNameBuff
}
type urlEncodedPayload struct {
Values []keyValuePair
}
type jsonEncodedPayload struct {
payload any
}
func newHTTPRequest(uri string) *httpRequest {
return &httpRequest{URL: uri, Client: http.DefaultClient}
}
func (r *httpRequest) addParameter(name, value string) {
if r.Parameters == nil {
r.Parameters = make(map[string][]string)
}
r.Parameters[name] = append(r.Parameters[name], value)
}
func (r *httpRequest) setClient(c *http.Client) {
r.Client = c
}
func (r *httpRequest) setBasicAuth(user, password string) {
r.BasicAuthUser = user
r.BasicAuthPassword = password
}
func newJSONEncodedPayload(payload any) *jsonEncodedPayload {
return &jsonEncodedPayload{payload: payload}
}
func (j *jsonEncodedPayload) getPayloadBuffer() (*bytes.Buffer, error) {
b, err := json.Marshal(j.payload)
if err != nil {
return nil, err
}
return bytes.NewBuffer(b), nil
}
func (*jsonEncodedPayload) getContentType() (string, error) {
return "application/json", nil
}
func (*jsonEncodedPayload) getValues() []keyValuePair {
return nil
}
func newUrlEncodedPayload() *urlEncodedPayload {
return &urlEncodedPayload{}
}
func (f *urlEncodedPayload) addValue(key, value string) {
f.Values = append(f.Values, keyValuePair{key: key, value: value})
}
func (f *urlEncodedPayload) getPayloadBuffer() (*bytes.Buffer, error) {
data := url.Values{}
for _, keyVal := range f.Values {
data.Add(keyVal.key, keyVal.value)
}
return bytes.NewBufferString(data.Encode()), nil
}
func (*urlEncodedPayload) getContentType() (string, error) {
return "application/x-www-form-urlencoded", nil
}
func (f *urlEncodedPayload) getValues() []keyValuePair {
return f.Values
}
func (r *httpResponse) parseFromJSON(v any) error {
return json.Unmarshal(r.Data, v)
}
func NewFormDataPayload() *FormDataPayload {
return &FormDataPayload{}
}
func (f *FormDataPayload) getValues() []keyValuePair {
return f.Values
}
func (f *FormDataPayload) addValue(key, value string) {
f.Values = append(f.Values, keyValuePair{key: key, value: value})
}
func (f *FormDataPayload) addFile(key, file string) {
f.Files = append(f.Files, keyValuePair{key: key, value: file})
}
func (f *FormDataPayload) addBuffer(key, file string, buff []byte) {
f.Buffers = append(f.Buffers, keyNameBuff{key: key, name: file, value: buff})
}
func (f *FormDataPayload) addReadCloser(key, name string, rc io.ReadCloser) {
f.ReadClosers = append(f.ReadClosers, keyNameRC{key: key, name: name, value: rc})
}
func (f *FormDataPayload) getPayloadBuffer() (*bytes.Buffer, error) {
data := &bytes.Buffer{}
writer := multipart.NewWriter(data)
defer writer.Close()
for _, keyVal := range f.Values {
tmp, err := writer.CreateFormField(keyVal.key)
if err != nil {
return nil, err
}
_, err = tmp.Write([]byte(keyVal.value))
if err != nil {
return nil, err
}
}
for _, file := range f.Files {
err := func() error {
tmp, err := writer.CreateFormFile(file.key, path.Base(file.value))
if err != nil {
return err
}
fp, err := os.Open(file.value)
if err != nil {
return err
}
defer fp.Close()
_, err = io.Copy(tmp, fp)
if err != nil {
return err
}
return nil
}()
if err != nil {
return nil, err
}
}
for _, file := range f.ReadClosers {
err := func() error {
tmp, err := writer.CreateFormFile(file.key, file.name)
if err != nil {
return err
}
defer file.value.Close()
_, err = io.Copy(tmp, file.value)
if err != nil {
return err
}
return nil
}()
if err != nil {
return nil, err
}
}
for _, buff := range f.Buffers {
tmp, err := writer.CreateFormFile(buff.key, buff.name)
if err != nil {
return nil, err
}
r := bytes.NewReader(buff.value)
_, err = io.Copy(tmp, r)
if err != nil {
return nil, err
}
}
// TODO(vtopc): getPayloadBuffer is not just a getter, it also sets the content type
f.contentType = writer.FormDataContentType()
return data, nil
}
func (f *FormDataPayload) getContentType() (string, error) {
if f.contentType == "" {
_, err := f.getPayloadBuffer()
if err != nil {
return "", err
}
}
return f.contentType, nil
}
func (r *httpRequest) addHeader(name, value string) {
if r.Headers == nil {
r.Headers = make(map[string]string)
}
r.Headers[name] = value
}
func (r *httpRequest) makeGetRequest(ctx context.Context) (*httpResponse, error) {
return r.makeRequest(ctx, http.MethodGet, nil)
}
func (r *httpRequest) makePostRequest(ctx context.Context, payload payload) (*httpResponse, error) {
return r.makeRequest(ctx, http.MethodPost, payload)
}
func (r *httpRequest) makePutRequest(ctx context.Context, payload payload) (*httpResponse, error) {
return r.makeRequest(ctx, http.MethodPut, payload)
}
func (r *httpRequest) makeDeleteRequest(ctx context.Context) (*httpResponse, error) {
return r.makeRequest(ctx, http.MethodDelete, nil)
}
func (r *httpRequest) NewRequest(ctx context.Context, method string, payload payload) (*http.Request, error) {
uri, err := r.generateUrlWithParameters()
if err != nil {
return nil, err
}
var body io.Reader
if payload != nil {
if body, err = payload.getPayloadBuffer(); err != nil {
return nil, err
}
} else {
body = nil
}
req, err := http.NewRequestWithContext(ctx, method, uri, body)
if err != nil {
return nil, err
}
if payload != nil {
contentType, err := payload.getContentType()
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", contentType)
}
if r.BasicAuthUser != "" && r.BasicAuthPassword != "" {
req.SetBasicAuth(r.BasicAuthUser, r.BasicAuthPassword)
}
for header, value := range r.Headers {
// Special case, override the Host header
if header == "Host" {
req.Host = value
continue
}
req.Header.Add(header, value)
}
return req, nil
}
func (r *httpRequest) makeRequest(ctx context.Context, method string, payload payload) (*httpResponse, error) {
req, err := r.NewRequest(ctx, method, payload)
if err != nil {
return nil, err
}
if Debug {
if CaptureCurlOutput {
r.mu.Lock()
r.capturedCurlOutput = curlString(req, payload)
r.mu.Unlock()
} else {
fmt.Println(curlString(req, payload))
}
}
resp, err := r.Client.Do(req)
if err != nil {
var urlErr *url.Error
if errors.As(err, &urlErr) && urlErr != nil && errors.Is(urlErr.Err, io.EOF) {
return nil, errors.Wrap(err, "remote server prematurely closed connection")
}
return nil, errors.Wrap(err, "while making http request")
}
defer resp.Body.Close()
response := httpResponse{
Code: resp.StatusCode,
}
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "while reading response body")
}
response.Data = responseBody
return &response, nil
}
func (r *httpRequest) generateUrlWithParameters() (string, error) {
uri, err := url.Parse(r.URL)
if err != nil {
return "", err
}
if !validURL.MatchString(uri.Path) {
return "", errors.New(`APIBase must end with a /v1, /v2, /v3 or /v4; SetAPIBase("https://host/v3")`)
}
q := uri.Query()
if len(r.Parameters) > 0 {
for name, values := range r.Parameters {
for _, value := range values {
q.Add(name, value)
}
}
}
uri.RawQuery = q.Encode()
return uri.String(), nil
}
func curlString(req *http.Request, p payload) string {
parts := []string{"curl", "-i", "-X", req.Method, req.URL.String()}
for key, value := range req.Header {
if key == "Authorization" {
parts = append(parts, fmt.Sprintf("-H \"%s: %s\"", key, "<redacted>"))
} else {
parts = append(parts, fmt.Sprintf("-H \"%s: %s\"", key, value[0]))
}
}
// Special case for Host
if req.Host != "" {
parts = append(parts, fmt.Sprintf("-H \"Host: %s\"", req.Host))
}
if p != nil {
contentType, _ := p.getContentType()
if contentType == "application/json" {
b, err := p.getPayloadBuffer()
if err != nil {
return "Unable to get payload buffer: " + err.Error()
}
parts = append(parts, fmt.Sprintf("--data '%s'", b.String()))
} else {
for _, param := range p.getValues() {
parts = append(parts, fmt.Sprintf(" -F %s='%s'", param.key, param.value))
}
}
}
return strings.Join(parts, " ")
}