-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.go
More file actions
703 lines (608 loc) · 22 KB
/
Copy pathrequest.go
File metadata and controls
703 lines (608 loc) · 22 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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// Copyright 2020 The ZKits Project Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package requester
import (
"bytes"
"context"
"encoding"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/edoger/zkits-requester/internal"
)
var (
// ErrEmptyRequestURL represents an empty request url error.
// When sending a request, this error will be returned if the given request url is empty.
ErrEmptyRequestURL = errors.New("empty request url")
// ErrInvalidRequestBody indicates an invalid request body error.
// When sending a request, if the bound request body cannot be recognized, this error is returned.
ErrInvalidRequestBody = errors.New("invalid request body")
// ErrEmptyUploadBody represents an empty upload body error.
// When sending an upload request, this error is returned when the upload data is empty.
ErrEmptyUploadBody = errors.New("empty upload body")
// ErrInvalidUploadBody indicates an invalid upload body error.
// When sending an upload request, this error is returned when the bound upload data is invalid.
ErrInvalidUploadBody = errors.New("invalid upload body")
)
// Request interface defines client requests.
type Request interface {
// WithMethod adds the default request method of the current request.
WithMethod(string) Request
// WithResponder adds the given responder to the current request.
WithResponder(Responder) Request
// WithHeader adds a request header to the current request.
// If the given request header value is an empty string, the corresponding request
// header will be deleted.
WithHeader(string, string) Request
// WithHeaderValue adds a request header to the current request.
// This method will automatically convert the given parameter value to a string.
WithHeaderValue(string, interface{}) Request
// WithContentType adds the ContentType header information of the current request.
WithContentType(string) Request
// WithHeaders adds and replaces some headers to the current request.
WithHeaders(http.Header) Request
// WithContext adds a context to the current request.
// If the given context is nil, context.Background() is automatically used.
WithContext(context.Context) Request
// WithQuery adds a query parameter to the current request.
WithQuery(string, string) Request
// WithQueryValue adds a query parameter to the current request.
// This method will automatically convert the given parameter value to a string.
WithQueryValue(string, interface{}) Request
// WithQueries adds and replaces some query parameters to the current request.
WithQueries(url.Values) Request
// WithTimeout adds a timeout for the current request.
// If the given timeout period is zero, the client's timeout setting is used.
WithTimeout(time.Duration) Request
// WithBody adds request body to the current request.
WithBody(interface{}) Request
// WithJSONBody adds the request body as json.
// This method will force set "Content-Type" to "application/json".
WithJSONBody(interface{}) Request
// WithRawJSONBody adds the request body as raw json.
// This method will force set "Content-Type" to "application/json".
WithRawJSONBody([]byte) Request
// WithXMLBody adds the request body as xml.
// This method will force set "Content-Type" to "application/xml".
WithXMLBody(interface{}) Request
// WithRawXMLBody adds the request body as raw xml.
// This method will force set "Content-Type" to "application/xml".
WithRawXMLBody([]byte) Request
// WithFormBody adds the request body as form (urlencoded).
// This method will force set "Content-Type" to "application/x-www-form-urlencoded".
WithFormBody(url.Values) Request
// WithFormBodyMap adds the request body key-value map as form (urlencoded).
// This method will force set "Content-Type" to "application/x-www-form-urlencoded".
WithFormBodyMap(body map[string]interface{}) Request
// Head sends the current request and returns the received response.
// This method will send the request using the HEAD method.
Head() (Response, error)
// Get sends the current request and returns the received response.
// This method will send the request using the GET method.
Get() (Response, error)
// Post sends the current request and returns the received response.
// This method will send the request using the POST method.
Post() (Response, error)
// Send sends the current request and returns the received response.
Send() (Response, error)
// SendBy sends the current request and returns the received response.
// This method will send the request using the given request method.
SendBy(string) (Response, error)
// WithFormDataField adds a form data for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
WithFormDataField(string, interface{}) Request
// WithFormDataFields adds a form data key-value map for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
WithFormDataFields(fields map[string]interface{}) Request
// WithFormDataFile adds a file target for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
// This method supports adding string paths, opened file descriptors and
// downstream uploaded files as upload targets.
WithFormDataFile(string, interface{}) Request
// WithFormDataFileFromReader adds an upload target to the current request from
// the given reader and file name.
// If the given reader is nil, delete the corresponding form key.
WithFormDataFileFromReader(string, string, io.Reader) Request
// ClearFormData removes all uploaded form data from the current request.
// If you need to reuse the current request instance to send multiple upload requests,
// you should clean up each time before setting new form data (for the added file descriptor,
// because the position of the cursor is uncertain, it may cause unexpected results ).
ClearFormData() Request
// Upload sends the current upload request and receives the response.
// This method will send the request using the POST method.
Upload() (Response, error)
// UploadBy sends the current upload request and receives the response.
// This method will send the request using the given request method.
// This method only supports POST method and PUT method.
UploadBy(string) (Response, error)
// Clear cleans up the current request instance so that it can be reused.
// This method will not cut the connection with the client, nor will it
// change the request url.
Clear() Request
}
// The request type is a built-in implementation of the Request interface.
type request struct {
client *client
uri string
method string
headers http.Header
ctx context.Context
query url.Values
timeout time.Duration
responder Responder
body interface{}
bodyFormData map[string][]*formDataValue
bodyEncoder string
bodyType string
}
// The formDataValue type defines a single upload form data.
type formDataValue struct {
field string
file interface{}
}
// WithMethod adds the default request method of the current request.
func (r *request) WithMethod(method string) Request {
r.method = method
return r
}
// WithResponder adds the given responder to the current request.
func (r *request) WithResponder(responder Responder) Request {
r.responder = responder
return r
}
// WithHeader adds a request header to the current request.
// If the given request header value is an empty string, the corresponding request
// header will be deleted.
func (r *request) WithHeader(key, value string) Request {
if value == "" {
if len(r.headers) > 0 {
r.headers.Del(key)
}
return r
}
if r.headers == nil {
r.headers = make(http.Header, 1)
}
r.headers.Set(key, value)
return r
}
// WithHeaderValue adds a request header to the current request.
// This method will automatically convert the given parameter value to a string.
func (r *request) WithHeaderValue(key string, value interface{}) Request {
return r.WithHeader(key, internal.ToString(value))
}
// WithContentType adds the ContentType header information of the current request.
func (r *request) WithContentType(ct string) Request {
r.WithHeader("Content-Type", ct)
return r
}
// WithHeaders adds and replaces some headers to the current request.
func (r *request) WithHeaders(headers http.Header) Request {
r.headers = headers
return r
}
// WithContext adds a context to the current request.
// If the given context is nil, context.Background() is automatically used.
func (r *request) WithContext(ctx context.Context) Request {
r.ctx = ctx
return r
}
// WithQuery adds a query parameter to the current request.
func (r *request) WithQuery(key, value string) Request {
if r.query == nil {
r.query = make(url.Values, 1)
}
r.query.Set(key, value)
return r
}
// WithQueryValue adds a query parameter to the current request.
// This method will automatically convert the given parameter value to a string.
func (r *request) WithQueryValue(key string, value interface{}) Request {
return r.WithQuery(key, internal.ToString(value))
}
// WithQueries adds and replaces some query parameters to the current request.
func (r *request) WithQueries(qs url.Values) Request {
r.query = qs
return r
}
// WithTimeout adds a timeout for the current request.
// If the given timeout period is zero, the client's timeout setting is used.
func (r *request) WithTimeout(t time.Duration) Request {
r.timeout = t
return r
}
// WithBody adds request body to the current request.
func (r *request) WithBody(body interface{}) Request {
r.body = body
r.bodyEncoder = ""
r.bodyType = ""
return r
}
// WithJSONBody adds the request body as json.
// This method will force set "Content-Type" to "application/json".
func (r *request) WithJSONBody(body interface{}) Request {
r.body = body
r.bodyEncoder = "json"
r.bodyType = "application/json"
return r
}
// WithRawJSONBody adds the request body as raw json.
// This method will force set "Content-Type" to "application/json".
func (r *request) WithRawJSONBody(body []byte) Request {
r.body = body
r.bodyEncoder = ""
r.bodyType = "application/json"
return r
}
// WithXMLBody adds the request body as xml.
// This method will force set "Content-Type" to "application/xml".
func (r *request) WithXMLBody(body interface{}) Request {
r.body = body
r.bodyEncoder = "xml"
r.bodyType = "application/xml"
return r
}
// WithRawXMLBody adds the request body as raw xml.
// This method will force set "Content-Type" to "application/xml".
func (r *request) WithRawXMLBody(body []byte) Request {
r.body = body
r.bodyEncoder = ""
r.bodyType = "application/xml"
return r
}
// WithFormBody adds the request body as form (urlencoded).
// This method will force set "Content-Type" to "application/x-www-form-urlencoded".
func (r *request) WithFormBody(body url.Values) Request {
r.body = body
r.bodyEncoder = ""
r.bodyType = "application/x-www-form-urlencoded"
return r
}
// WithFormBodyMap adds the request body key-value map as form (urlencoded).
// This method will force set "Content-Type" to "application/x-www-form-urlencoded".
func (r *request) WithFormBodyMap(body map[string]interface{}) Request {
values := make(url.Values, len(body))
for key, value := range body {
values.Set(key, internal.ToString(value))
}
return r.WithFormBody(values)
}
// Head sends the current request and returns the received response.
// This method will send the request using the HEAD method.
func (r *request) Head() (Response, error) {
return r.SendBy(http.MethodHead)
}
// Get sends the current request and returns the received response.
// This method will send the request using the GET method.
func (r *request) Get() (Response, error) {
return r.SendBy(http.MethodGet)
}
// Post sends the current request and returns the received response.
// This method will send the request using the POST method.
func (r *request) Post() (Response, error) {
return r.SendBy(http.MethodPost)
}
// Send sends the current request and returns the received response.
func (r *request) Send() (Response, error) {
return r.SendBy(r.method)
}
// SendBy sends the current request and returns the received response.
// This method will send the request using the given request method.
func (r *request) SendBy(method string) (Response, error) {
if r.uri == "" {
return nil, ErrEmptyRequestURL
}
if o, err := r.send(strings.ToUpper(method)); err != nil {
return nil, err
} else {
// For HEAD requests, we ignore the response body.
return r.fromResponder(o, o.Request.Method == http.MethodHead)
}
}
// Build the Response instance from the responder.
func (r *request) fromResponder(o *http.Response, noBody bool) (Response, error) {
if r.responder != nil {
return r.responder(o, noBody)
}
if r.client.responder != nil {
return r.client.responder(o, noBody)
}
return NewResponse(o, noBody)
}
// The send method sends the current request and returns the received response.
func (r *request) send(method string) (*http.Response, error) {
body, err := r.makeBodyReader()
if err != nil {
return nil, err
}
ctx, cancel := r.getContext()
if cancel != nil {
// The context must be explicitly cancelled after the end of the request,
// so that the resources of this request can be released quickly.
defer cancel()
}
req, err := http.NewRequestWithContext(ctx, method, r.uri, body)
if err != nil {
return nil, err
}
// Add common request headers provided by the client.
if len(r.client.headers) > 0 {
for key, values := range r.client.headers {
req.Header[key] = values
}
}
// Add request headers provided by the current request.
if len(r.headers) > 0 {
for key, values := range r.headers {
req.Header[key] = values
}
}
// If the type of the request body is known, the Content-Type field of the
// request header is forced to be set.
if r.bodyType != "" {
req.Header.Set("Content-Type", r.bodyType)
}
if len(r.query) > 0 {
if req.URL.RawQuery == "" {
req.URL.RawQuery = r.query.Encode()
} else {
// If query parameters are already attached to the target URL,
// we need to overwrite the set query parameters to the target URL.
qs := req.URL.Query()
for key, values := range r.query {
qs[key] = values
}
req.URL.RawQuery = qs.Encode()
}
}
if r.client.http == nil {
return internal.Client.Do(req)
} else {
return r.client.http.Do(req)
}
}
// Gets the request context.
func (r *request) getContext() (context.Context, context.CancelFunc) {
ctx := r.ctx
if ctx == nil {
ctx = context.Background()
}
if r.timeout > 0 {
return context.WithTimeout(ctx, r.timeout)
}
if r.client.timeout > 0 {
return context.WithTimeout(ctx, r.client.timeout)
}
return ctx, nil
}
// The makeBodyReader method returns the current request body as a io.Reader.
func (r *request) makeBodyReader() (io.Reader, error) {
if r.body == nil {
return nil, nil
}
if r.bodyEncoder != "" {
switch r.bodyEncoder {
case "json":
if data, err := json.Marshal(r.body); err != nil {
return nil, err
} else {
return bytes.NewReader(data), nil
}
case "xml":
if data, err := xml.Marshal(r.body); err != nil {
return nil, err
} else {
return bytes.NewReader(data), nil
}
}
}
switch body := r.body.(type) {
case string:
return strings.NewReader(body), nil
case []byte:
return bytes.NewReader(body), nil
case url.Values:
return strings.NewReader(body.Encode()), nil
case io.Reader:
return body, nil
case fmt.Stringer:
return strings.NewReader(body.String()), nil
case encoding.TextMarshaler:
if data, err := body.MarshalText(); err != nil {
return nil, err
} else {
return bytes.NewReader(data), nil
}
}
return nil, ErrInvalidRequestBody
}
// WithFormDataField adds a form data for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
func (r *request) WithFormDataField(key string, value interface{}) Request {
if value == nil {
return r.withFormData(key, nil)
}
return r.withFormData(key, &formDataValue{field: internal.ToString(value)})
}
// WithFormDataFields adds a form data key-value map for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
func (r *request) WithFormDataFields(fields map[string]interface{}) Request {
for key, value := range fields {
r.WithFormDataField(key, value)
}
return r
}
// WithFormDataFile adds a file target for uploading to the current request.
// If the given form value is nil, delete the corresponding form key.
// This method supports adding string paths, opened file descriptors and
// downstream uploaded files as upload targets.
func (r *request) WithFormDataFile(key string, value interface{}) Request {
if value == nil {
return r.withFormData(key, nil)
}
return r.withFormData(key, &formDataValue{file: value})
}
// The formDataFileReader type is used to warp the io.Reader and a file name
// into a file target for upload.
type formDataFileReader struct {
name string
reader io.Reader
}
// WithFormDataFileFromReader adds an upload target to the current request from
// the given reader and file name.
// If the given reader is nil, delete the corresponding form key.
func (r *request) WithFormDataFileFromReader(key string, name string, reader io.Reader) Request {
if reader == nil {
return r.withFormData(key, nil)
}
return r.withFormData(key, &formDataValue{file: &formDataFileReader{name: name, reader: reader}})
}
// The withFormData method adds an upload form data to the current request.
func (r *request) withFormData(key string, value *formDataValue) *request {
if value == nil {
if len(r.bodyFormData) > 0 {
delete(r.bodyFormData, key)
}
return r
}
if r.bodyFormData == nil {
r.bodyFormData = make(map[string][]*formDataValue, 1)
}
r.bodyFormData[key] = append(r.bodyFormData[key], value)
return r
}
// ClearFormData removes all uploaded form data from the current request.
// If you need to reuse the current request instance to send multiple upload requests,
// you should clean up each time before setting new form data (for the added file descriptor,
// because the position of the cursor is uncertain, it may cause unexpected results ).
func (r *request) ClearFormData() Request {
r.bodyFormData = nil
return r
}
// Upload sends the current upload request and receives the response.
// This method will send the request using the POST method.
func (r *request) Upload() (Response, error) {
return r.UploadBy(http.MethodPost)
}
// UploadBy sends the current upload request and receives the response.
// This method will send the request using the given request method.
// This method only supports POST method and PUT method.
func (r *request) UploadBy(method string) (Response, error) {
if r.uri == "" {
return nil, ErrEmptyRequestURL
}
method = strings.ToUpper(method)
if method != http.MethodPost && method != http.MethodPut {
return nil, fmt.Errorf("unsupported upload method: %s", method)
}
if len(r.bodyFormData) == 0 {
return nil, ErrEmptyUploadBody
}
b := new(bytes.Buffer)
w := multipart.NewWriter(b)
keys := make([]string, 0, len(r.bodyFormData))
for key := range r.bodyFormData {
keys = append(keys, key)
}
if len(keys) > 1 {
sort.Strings(keys)
}
for i, j := 0, len(keys); i < j; i++ {
for m, n := 0, len(r.bodyFormData[keys[i]]); m < n; m++ {
if r.bodyFormData[keys[i]][m].file == nil {
// This is normal form data.
if err := w.WriteField(keys[i], r.bodyFormData[keys[i]][m].field); err != nil {
return nil, err
}
continue
}
switch v := r.bodyFormData[keys[i]][m].file.(type) {
case string:
if err := internal.ShouldBeRegularFile(os.Stat(v)); err != nil {
return nil, err
}
if err := internal.WriteFormDataFromFilePath(keys[i], v, w); err != nil {
return nil, err
}
case *os.File:
if err := internal.ShouldBeRegularFile(v.Stat()); err != nil {
return nil, err
}
// Here we cannot determine the offset in the file pointed to by the file descriptor,
// we only read all the file content as upload content.
// After we finish reading, we do not return the original position of the cursor and
// close the file descriptor, because we are not sure whether this file is used elsewhere.
if err := internal.WriteFormDataFromReader(keys[i], filepath.Base(v.Name()), w, v); err != nil {
return nil, err
}
case *multipart.FileHeader:
// For interim uploads, we read data directly from downstream uploaded files.
if err := internal.WriteFormDataFromFileHeader(keys[i], v, w); err != nil {
return nil, err
}
case *formDataFileReader:
if err := internal.WriteFormDataFromReader(keys[i], filepath.Base(v.name), w, v.reader); err != nil {
return nil, err
}
default:
return nil, ErrInvalidUploadBody
}
}
}
// It must be closed before the request is sent, otherwise the content of
// the request body will be incomplete.
if err := w.Close(); err != nil {
return nil, err
}
r.body = b
r.bodyEncoder = ""
r.bodyType = w.FormDataContentType()
if o, err := r.send(method); err != nil {
return nil, err
} else {
return r.fromResponder(o, false)
}
}
// Clear cleans up the current request instance so that it can be reused.
// This method will not cut the connection with the client, nor will it
// change the request url.
func (r *request) Clear() Request {
r.method = ""
r.headers = nil
r.ctx = nil
r.query = nil
r.timeout = 0
r.body = nil
r.bodyEncoder = ""
r.bodyType = ""
r.responder = nil
return r.ClearFormData()
}
// The reset method resets the current instance.
func (r *request) reset() *request {
r.Clear()
r.client = nil
r.uri = ""
return r
}