forked from parnurzeal/gorequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorequest.go
1585 lines (1457 loc) · 46.2 KB
/
gorequest.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
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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package gorequest inspired by Nodejs SuperAgent provides easy-way to write http client
package gorequest
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net"
"net/http"
"net/http/cookiejar"
"net/http/httputil"
"net/textproto"
"net/url"
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"time"
"github.com/spf13/cast"
"golang.org/x/net/publicsuffix"
"gopkg.in/h2non/gock.v1"
"moul.io/http2curl"
)
type Request *http.Request
type Response *http.Response
type superAgentRetryable struct {
RetryableStatus []int
RetryerTime time.Duration
RetryerCount int
Attempt int
Enable bool
}
// A SuperAgent is a object storing all request data for client.
type SuperAgent struct {
Url string
Method string
Header http.Header
TargetType string
ForceType string
Data map[string]interface{}
SliceData []interface{}
FormData url.Values
QueryData url.Values
FileData []File
BounceToRawString bool
RawString string
Client *http.Client
Transport *http.Transport
Cookies []*http.Cookie
Errors []error
BasicAuth struct{ Username, Password string }
Debug bool
CurlCommand bool
logger Logger
Retryable superAgentRetryable
DoNotClearSuperAgent bool
isClone bool
ctx context.Context
Stats Stats
isMock bool
}
var DisableTransportSwap = false
// New used to create a new SuperAgent object.
func New() *SuperAgent {
cookiejarOptions := cookiejar.Options{
PublicSuffixList: publicsuffix.List,
}
jar, _ := cookiejar.New(&cookiejarOptions)
debug := os.Getenv("GOREQUEST_DEBUG") == "1"
s := &SuperAgent{
TargetType: TypeJSON,
Data: make(map[string]interface{}),
Header: http.Header{},
RawString: "",
SliceData: []interface{}{},
FormData: url.Values{},
QueryData: url.Values{},
FileData: make([]File, 0),
BounceToRawString: false,
Client: &http.Client{Jar: jar},
Transport: &http.Transport{},
Cookies: make([]*http.Cookie, 0),
Errors: nil,
BasicAuth: struct{ Username, Password string }{},
Debug: debug,
CurlCommand: false,
logger: log.New(os.Stderr, "[gorequest]", log.LstdFlags),
isClone: false,
ctx: nil,
Stats: Stats{},
isMock: false,
}
// disable keep alives by default, see this issue https://github.com/parnurzeal/gorequest/issues/75
s.Transport.DisableKeepAlives = true
return s
}
// Clone returns a copy of this superagent. Useful if you want to reuse the client/settings
// concurrently.
// Note: This does a shallow copy of the parent. So you will need to be
// careful of Data provided
// Note: It also directly re-uses the client and transport. If you modify the Timeout,
// or RedirectPolicy on a clone, the clone will have a new http.client. It is recommended
// that the base request set your timeout and redirect polices, and no modification of
// the client or transport happen after cloning.
// Note: DoNotClearSuperAgent is forced to "true" after Clone
func (s *SuperAgent) Clone() *SuperAgent {
clone := &SuperAgent{
Url: s.Url,
Method: s.Method,
Header: http.Header(cloneMapArray(s.Header)),
TargetType: s.TargetType,
ForceType: s.ForceType,
Data: shallowCopyData(s.Data),
SliceData: shallowCopyDataSlice(s.SliceData),
FormData: url.Values(cloneMapArray(s.FormData)),
QueryData: url.Values(cloneMapArray(s.QueryData)),
FileData: shallowCopyFileArray(s.FileData),
BounceToRawString: s.BounceToRawString,
RawString: s.RawString,
Client: s.Client,
Transport: s.Transport,
Cookies: shallowCopyCookies(s.Cookies),
Errors: shallowCopyErrors(s.Errors),
BasicAuth: s.BasicAuth,
Debug: s.Debug,
CurlCommand: s.CurlCommand,
logger: s.logger, // thread safe.. anyway
Retryable: copyRetryable(s.Retryable),
DoNotClearSuperAgent: true,
isClone: true,
ctx: s.ctx,
Stats: copyStats(s.Stats),
isMock: s.isMock,
}
return clone
}
func (s *SuperAgent) Context(ctx context.Context) *SuperAgent {
s.ctx = ctx
return s
}
// Mock will enable gock, http mocking for net/http
func (s *SuperAgent) Mock() *SuperAgent {
gock.InterceptClient(s.Client)
s.isMock = true
return s
}
// SetDebug enable the debug mode which logs request/response detail.
func (s *SuperAgent) SetDebug(enable bool) *SuperAgent {
s.Debug = enable
return s
}
// SetCurlCommand enable the curlcommand mode which display a CURL command line.
func (s *SuperAgent) SetCurlCommand(enable bool) *SuperAgent {
s.CurlCommand = enable
return s
}
// SetDoNotClearSuperAgent enable the DoNotClear mode for not clearing super agent and reuse for the next request.
func (s *SuperAgent) SetDoNotClearSuperAgent(enable bool) *SuperAgent {
s.DoNotClearSuperAgent = enable
return s
}
// SetLogger set the logger which is the default logger to the SuperAgent instance.
func (s *SuperAgent) SetLogger(logger Logger) *SuperAgent {
s.logger = logger
return s
}
// DisableCompression disable the compression of http.Client.
func (s *SuperAgent) DisableCompression() *SuperAgent {
s.Transport.DisableCompression = true
return s
}
// ClearSuperAgent clear SuperAgent data for another new request.
func (s *SuperAgent) ClearSuperAgent() {
if s.DoNotClearSuperAgent {
return
}
s.Url = ""
s.Method = ""
s.Header = http.Header{}
s.Data = make(map[string]interface{})
s.SliceData = []interface{}{}
s.FormData = url.Values{}
s.QueryData = url.Values{}
s.FileData = make([]File, 0)
s.BounceToRawString = false
s.RawString = ""
s.ForceType = ""
s.TargetType = TypeJSON
s.Cookies = make([]*http.Cookie, 0)
s.Errors = nil
s.ctx = nil
s.Stats = Stats{}
}
// CustomMethod is just a wrapper to initialize SuperAgent instance by method string.
func (s *SuperAgent) CustomMethod(method, targetUrl string) *SuperAgent {
switch method {
case POST:
return s.Post(targetUrl)
case GET:
return s.Get(targetUrl)
case HEAD:
return s.Head(targetUrl)
case PUT:
return s.Put(targetUrl)
case DELETE:
return s.Delete(targetUrl)
case PATCH:
return s.Patch(targetUrl)
case OPTIONS:
return s.Options(targetUrl)
default:
s.ClearSuperAgent()
s.Method = method
s.Url = targetUrl
s.Errors = nil
return s
}
}
func (s *SuperAgent) Get(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = GET
s.Url = targetUrl
s.Errors = nil
s.TargetType = ""
return s
}
func (s *SuperAgent) Post(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = POST
s.Url = targetUrl
s.Errors = nil
return s
}
func (s *SuperAgent) Head(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = HEAD
s.Url = targetUrl
s.Errors = nil
return s
}
func (s *SuperAgent) Put(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = PUT
s.Url = targetUrl
s.Errors = nil
return s
}
func (s *SuperAgent) Delete(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = DELETE
s.Url = targetUrl
s.Errors = nil
return s
}
func (s *SuperAgent) Patch(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = PATCH
s.Url = targetUrl
s.Errors = nil
return s
}
func (s *SuperAgent) Options(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = OPTIONS
s.Url = targetUrl
s.Errors = nil
return s
}
// Set is used for setting header fields,
// this will overwrite the existed values of Header through AppendHeader().
// Example. To set `Accept` as `application/json`
//
// gorequest.New().
// Post("https://httpbin.org/post").
// Set("Accept", "application/json").
// End()
func (s *SuperAgent) Set(param string, value string) *SuperAgent {
s.Header.Set(param, value)
return s
}
// SetHeaders is used for setting all your headers with the use of a map or a struct.
// It uses AppendHeader() method so it allows for multiple values of the same header
// Example. To set the following struct as headers, simply do
//
// headers := apiHeaders{Accept: "application/json", Content-Type: "text/html", X-Frame-Options: "deny"}
// gorequest.New().
// Post("apiEndPoint").
// Set(headers).
// End()
func (s *SuperAgent) SetHeaders(headers interface{}) *SuperAgent {
switch v := reflect.ValueOf(headers); v.Kind() {
case reflect.Struct:
s.setHeadersStruct(v.Interface())
case reflect.Map:
s.setHeadersMap(v.Interface())
default:
return s
}
return s
}
func (s *SuperAgent) setHeadersMap(content interface{}) *SuperAgent {
return s.setHeadersStruct(content)
}
// SendStruct (similar to SendString) returns SuperAgent's itself for any next chain and takes content interface{} as a parameter.
// Its duty is to transform interface{} (implicitly always a struct) into s.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End() func.
func (s *SuperAgent) setHeadersStruct(content interface{}) *SuperAgent {
if marshalContent, err := json.Marshal(content); err != nil {
s.Errors = append(s.Errors, err)
} else {
var val map[string]interface{}
d := json.NewDecoder(bytes.NewBuffer(marshalContent))
d.UseNumber()
if err := d.Decode(&val); err != nil {
s.Errors = append(s.Errors, err)
} else {
for k, v := range val {
strValue, err := cast.ToStringE(v)
if err != nil {
// TODO: log err?
continue
}
s.AppendHeader(k, strValue)
}
}
}
return s
}
// AppendHeader is used for setting headers with multiple values,
// Example. To set `Accept` as `application/json, text/plain`
//
// gorequest.New().
// Post("https://httpbin.org/post").
// AppendHeader("Accept", "application/json").
// AppendHeader("Accept", "text/plain").
// End()
func (s *SuperAgent) AppendHeader(param string, value string) *SuperAgent {
s.Header.Add(param, value)
return s
}
// UserAgent is used for setting User-Agent into headers
// Example. To set `User-Agent` as `Custom user agent`
//
// gorequest.New().
// Post("https://httpbin.org/post").
// UserAgent("Custom user agent").
// End()
func (s *SuperAgent) UserAgent(ua string) *SuperAgent {
s.Header.Add("User-Agent", ua)
return s
}
// Retry is used for setting a Retryer policy
// Example. To set Retryer policy with 5 seconds between each attempt.
// 3 max attempt.
// And StatusBadRequest and StatusInternalServerError as RetryableStatus
//
// gorequest.New().
// Post("https://httpbin.org/post").
// Retry(3, 5 * time.Second, http.StatusBadRequest, http.StatusInternalServerError).
// End()
func (s *SuperAgent) Retry(retryerCount int, retryerTime time.Duration, statusCode ...int) *SuperAgent {
for _, code := range statusCode {
statusText := http.StatusText(code)
if len(statusText) == 0 {
s.Errors = append(s.Errors, fmt.Errorf("StatusCode '%d' doesn't exist in http package", code))
}
}
s.Retryable = struct {
RetryableStatus []int
RetryerTime time.Duration
RetryerCount int
Attempt int
Enable bool
}{
statusCode,
retryerTime,
retryerCount,
0,
true,
}
return s
}
// SetBasicAuth sets the basic authentication header
// Example. To set the header for username "myuser" and password "mypass"
//
// gorequest.New()
// Post("https://httpbin.org/post").
// SetBasicAuth("myuser", "mypass").
// End()
func (s *SuperAgent) SetBasicAuth(username string, password string) *SuperAgent {
s.BasicAuth = struct{ Username, Password string }{username, password}
return s
}
// AddCookie adds a cookie to the request. The behavior is the same as AddCookie on Request from net/http
func (s *SuperAgent) AddCookie(c *http.Cookie) *SuperAgent {
s.Cookies = append(s.Cookies, c)
return s
}
// AddCookies is a convenient method to add multiple cookies
func (s *SuperAgent) AddCookies(cookies []*http.Cookie) *SuperAgent {
s.Cookies = append(s.Cookies, cookies...)
return s
}
// Type is a convenience function to specify the data type to send.
// For example, to send data as `application/x-www-form-urlencoded` :
//
// gorequest.New().
// Post("/recipe").
// Type("form").
// Send(`{ "name": "egg benedict", "category": "brunch" }`).
// End()
//
// This will POST the body "name=egg benedict&category=brunch" to url /recipe
//
// GoRequest supports
//
// "text/html" uses "html"
// "application/json" uses "json"
// "application/xml" uses "xml"
// "text/plain" uses "text"
// "application/x-www-form-urlencoded" uses "urlencoded", "form" or "form-data"
//
func (s *SuperAgent) Type(typeStr string) *SuperAgent {
if _, ok := Types[typeStr]; ok {
s.ForceType = typeStr
} else {
s.Errors = append(s.Errors, fmt.Errorf("type func: incorrect type \"%s\"", typeStr))
}
return s
}
// Query function accepts either json string or strings which will form a query-string in url of GET method or body of POST method.
// For example, making "/search?query=bicycle&size=50x50&weight=20kg" using GET method:
//
// gorequest.New().
// Get("/search").
// Query(`{ query: 'bicycle' }`).
// Query(`{ size: '50x50' }`).
// Query(`{ weight: '20kg' }`).
// End()
//
// Or you can put multiple json values:
//
// gorequest.New().
// Get("/search").
// Query(`{ query: 'bicycle', size: '50x50', weight: '20kg' }`).
// End()
//
// Strings are also acceptable:
//
// gorequest.New().
// Get("/search").
// Query("query=bicycle&size=50x50").
// Query("weight=20kg").
// End()
//
// Or even Mixed! :)
//
// gorequest.New().
// Get("/search").
// Query("query=bicycle").
// Query(`{ size: '50x50', weight:'20kg' }`).
// End()
//
func (s *SuperAgent) Query(content interface{}) *SuperAgent {
switch v := reflect.ValueOf(content); v.Kind() {
case reflect.String:
s.queryString(v.String())
case reflect.Struct:
s.queryStruct(v.Interface())
case reflect.Map:
s.queryMap(v.Interface())
default:
}
return s
}
func (s *SuperAgent) queryStruct(content interface{}) *SuperAgent {
if marshalContent, err := json.Marshal(content); err != nil {
s.Errors = append(s.Errors, err)
} else {
var val map[string]interface{}
d := json.NewDecoder(bytes.NewBuffer(marshalContent))
d.UseNumber()
if err := d.Decode(&val); err != nil {
s.Errors = append(s.Errors, err)
} else {
for k, v := range val {
// k = strings.ToLower(k)
var queryVal string
switch t := v.(type) {
case string:
queryVal = t
case float64:
queryVal = strconv.FormatFloat(t, 'f', -1, 64)
case time.Time:
queryVal = t.Format(time.RFC3339)
case json.Number:
queryVal = string(t)
default:
j, err := json.Marshal(v)
if err != nil {
continue
}
queryVal = BytesToString(j)
}
s.QueryData.Add(k, queryVal)
}
}
}
return s
}
func (s *SuperAgent) queryString(content string) *SuperAgent {
var val map[string]string
if err := json.Unmarshal(StringToBytes(content), &val); err == nil {
for k, v := range val {
s.QueryData.Add(k, v)
}
} else {
if queryData, err := url.ParseQuery(content); err == nil {
for k, queryValues := range queryData {
for _, queryValue := range queryValues {
s.QueryData.Add(k, queryValue)
}
}
} else {
s.Errors = append(s.Errors, err)
}
// TODO: need to check correct format of 'field=val&field=val&...'
}
return s
}
func (s *SuperAgent) queryMap(content interface{}) *SuperAgent {
return s.queryStruct(content)
}
// Param as Go conventions accepts ; as a synonym for &. (https://github.com/golang/go/issues/2210)
// Thus, Query won't accept ; in a querystring if we provide something like fields=f1;f2;f3
// This Param is then created as an alternative method to solve this.
func (s *SuperAgent) Param(key string, value string) *SuperAgent {
s.QueryData.Add(key, value)
return s
}
// TLSClientConfig set TLSClientConfig for underling Transport.
// One example is you can use it to disable security check (https):
//
// gorequest.New().TLSClientConfig(&tls.Config{ InsecureSkipVerify: true}).
// Get("https://disable-security-check.com").
// End()
//
func (s *SuperAgent) TLSClientConfig(config *tls.Config) *SuperAgent {
s.safeModifyTransport()
s.Transport.TLSClientConfig = config
return s
}
// Proxy function accepts a proxy url string to setup proxy url for any request.
// It provides a convenience way to setup proxy which have advantages over usual old ways.
// One example is you might try to set `http_proxy` environment. This means you are setting proxy up for all the requests.
// You will not be able to send different request with different proxy unless you change your `http_proxy` environment again.
// Another example is using Golang proxy setting. This is normal prefer way to do but too verbase compared to GoRequest's Proxy:
//
// gorequest.New().Proxy("http://myproxy:9999").
// Post("http://www.google.com").
// End()
//
// To set no_proxy, just put empty string to Proxy func:
//
// gorequest.New().Proxy("").
// Post("http://www.google.com").
// End()
//
func (s *SuperAgent) Proxy(proxyUrl string) *SuperAgent {
parsedProxyUrl, err := url.Parse(proxyUrl)
if err != nil {
s.Errors = append(s.Errors, err)
} else if proxyUrl == "" {
s.safeModifyTransport()
s.Transport.Proxy = nil
} else {
s.safeModifyTransport()
s.Transport.Proxy = http.ProxyURL(parsedProxyUrl)
}
return s
}
// RedirectPolicy accepts a function to define how to handle redirects. If the
// policy function returns an error, the next Request is not made and the previous
// request is returned.
//
// The policy function's arguments are the Request about to be made and the
// past requests in order of oldest first.
func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) error) *SuperAgent {
s.safeModifyHttpClient()
s.Client.CheckRedirect = func(r *http.Request, v []*http.Request) error {
vv := make([]Request, len(v))
for i, r := range v {
vv[i] = Request(r)
}
return policy(Request(r), vv)
}
return s
}
// Send function accepts either json string or query strings which is usually used to assign data to POST or PUT method.
// Without specifying any type, if you give Send with json data, you are doing requesting in json format:
//
// gorequest.New().
// Post("/search").
// Send(`{ query: 'sushi' }`).
// End()
//
// While if you use at least one of querystring, GoRequest understands and automatically set the Content-Type to `application/x-www-form-urlencoded`
//
// gorequest.New().
// Post("/search").
// Send("query=tonkatsu").
// End()
//
// So, if you want to strictly send json format, you need to use Type func to set it as `json` (Please see more details in Type function).
// You can also do multiple chain of Send:
//
// gorequest.New().
// Post("/search").
// Send("query=bicycle&size=50x50").
// Send(`{ wheel: '4'}`).
// End()
//
// From v0.2.0, Send function provide another convenience way to work with Struct type. You can mix and match it with json and query string:
//
// type BrowserVersionSupport struct {
// Chrome string
// Firefox string
// }
// ver := BrowserVersionSupport{ Chrome: "37.0.2041.6", Firefox: "30.0" }
// gorequest.New().
// Post("/update_version").
// Send(ver).
// Send(`{"Safari":"5.1.10"}`).
// End()
//
// If you have set Type to text or Content-Type to text/plain, content will be sent as raw string in body instead of form
//
// gorequest.New().
// Post("/greet").
// Type("text").
// Send("hello world").
// End()
//
func (s *SuperAgent) Send(content interface{}) *SuperAgent {
// TODO: add normal text mode or other mode to Send func
switch v := reflect.ValueOf(content); v.Kind() {
case reflect.String:
s.SendString(v.String())
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: // includes rune
s.SendString(strconv.FormatInt(v.Int(), 10))
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: // includes byte
s.SendString(strconv.FormatUint(v.Uint(), 10))
case reflect.Float64:
s.SendString(strconv.FormatFloat(v.Float(), 'f', -1, 64))
case reflect.Float32:
s.SendString(strconv.FormatFloat(v.Float(), 'f', -1, 32))
case reflect.Bool:
s.SendString(strconv.FormatBool(v.Bool()))
case reflect.Struct:
s.SendStruct(v.Interface())
case reflect.Slice:
s.SendSlice(makeSliceOfReflectValue(v))
case reflect.Array:
s.SendSlice(makeSliceOfReflectValue(v))
case reflect.Ptr:
s.Send(v.Elem().Interface())
case reflect.Map:
s.SendMap(v.Interface())
default:
// TODO: leave default for handling other types in the future, such as complex numbers, (nested) maps, etc
return s
}
return s
}
func makeSliceOfReflectValue(v reflect.Value) (slice []interface{}) {
kind := v.Kind()
if kind != reflect.Slice && kind != reflect.Array {
return slice
}
slice = make([]interface{}, v.Len())
for i := 0; i < v.Len(); i++ {
slice[i] = v.Index(i).Interface()
}
return slice
}
// SendSlice (similar to SendString) returns SuperAgent's itself for any next chain and takes content []interface{} as a parameter.
// Its duty is to append slice of interface{} into s.SliceData ([]interface{}) which later changes into json array in the End() func.
func (s *SuperAgent) SendSlice(content []interface{}) *SuperAgent {
s.SliceData = append(s.SliceData, content...)
return s
}
func (s *SuperAgent) SendMap(content interface{}) *SuperAgent {
return s.SendStruct(content)
}
// SendStruct (similar to SendString) returns SuperAgent's itself for any next chain and takes content interface{} as a parameter.
// Its duty is to transform interface{} (implicitly always a struct) into s.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End() func.
func (s *SuperAgent) SendStruct(content interface{}) *SuperAgent {
if marshalContent, err := json.Marshal(content); err != nil {
s.Errors = append(s.Errors, err)
} else {
var val map[string]interface{}
d := json.NewDecoder(bytes.NewBuffer(marshalContent))
d.UseNumber()
if err := d.Decode(&val); err != nil {
s.Errors = append(s.Errors, err)
} else {
for k, v := range val {
s.Data[k] = v
}
}
}
return s
}
// SendString returns SuperAgent's itself for any next chain and takes content string as a parameter.
// Its duty is to transform String into s.Data (map[string]interface{}) which later changes into appropriate format such as json, form, text, etc. in the End func.
// Send implicitly uses SendString and you should use Send instead of this.
func (s *SuperAgent) SendString(content string) *SuperAgent {
if !s.BounceToRawString {
var val interface{}
d := json.NewDecoder(strings.NewReader(content))
d.UseNumber()
if err := d.Decode(&val); err == nil {
switch v := reflect.ValueOf(val); v.Kind() {
case reflect.Map:
for k, v := range val.(map[string]interface{}) {
s.Data[k] = v
}
// NOTE: if SendString(`{}`), will come into this case, but set nothing into s.Data
if len(s.Data) == 0 {
s.BounceToRawString = true
}
// add to SliceData
case reflect.Slice:
s.SendSlice(val.([]interface{}))
// bounce to rawstring if it is arrayjson, or others
default:
s.BounceToRawString = true
}
} else if formData, err := url.ParseQuery(content); err == nil {
for k, formValues := range formData {
for _, formValue := range formValues {
// make it array if already have key
if val, ok := s.Data[k]; ok {
var strArray []string
strArray = append(strArray, formValue)
// check if previous data is one string or array
switch oldValue := val.(type) {
case []string:
strArray = append(strArray, oldValue...)
case string:
strArray = append(strArray, oldValue)
}
s.Data[k] = strArray
} else {
// make it just string if does not already have same key
s.Data[k] = formValue
}
}
}
s.TargetType = TypeForm
} else {
s.BounceToRawString = true
}
}
// Dump all contents to RawString in case in the end user doesn't want json or form.
s.RawString += content
return s
}
type File struct {
Filename string
Fieldname string
MimeType string
Data []byte
}
// SendFile function works only with type "multipart". The function accepts one mandatory and up to three optional arguments. The mandatory (first) argument is the file.
// The function accepts a path to a file as string:
//
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile("./example_file.ext").
// End()
//
// File can also be a []byte slice of a already file read by eg. ioutil.ReadFile:
//
// b, _ := ioutil.ReadFile("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(b).
// End()
//
// Furthermore file can also be a os.File:
//
// f, _ := os.Open("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(f).
// End()
//
// The first optional argument (second argument overall) is the filename, which will be automatically determined when file is a string (path) or a os.File.
// When file is a []byte slice, filename defaults to "filename". In all cases the automatically determined filename can be overwritten:
//
// b, _ := ioutil.ReadFile("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(b, "my_custom_filename").
// End()
//
// The second optional argument (third argument overall) is the fieldname in the multipart/form-data request. It defaults to fileNUMBER (eg. file1), where number is ascending and starts counting at 1.
// So if you send multiple files, the fieldnames will be file1, file2, ... unless it is overwritten. If fieldname is set to "file" it will be automatically set to fileNUMBER, where number is the greatest existing number+1 unless
// a third argument skipFileNumbering is provided and true.
//
// b, _ := ioutil.ReadFile("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(b, "", "my_custom_fieldname"). // filename left blank, will become "example_file.ext"
// End()
//
// The third optional argument (fourth argument overall) is a bool value skipFileNumbering. It defaults to "false",
// if fieldname is "file" and skipFileNumbering is set to "false", the fieldname will be automatically set to
// fileNUMBER, where number is the greatest existing number+1.
//
// b, _ := ioutil.ReadFile("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(b, "filename", "my_custom_fieldname", false).
// End()
//
// The fourth optional argument (fifth argument overall) is the mimetype request form-data part. It defaults to "application/octet-stream".
//
// b, _ := ioutil.ReadFile("./example_file.ext")
// gorequest.New().
// Post("http://example.com").
// Type("multipart").
// SendFile(b, "filename", "my_custom_fieldname", false, "mime_type").
// End()
//
func (s *SuperAgent) SendFile(file interface{}, args ...interface{}) *SuperAgent {
filename := ""
fieldname := "file"
skipFileNumbering := false
fileType := "application/octet-stream"
if len(args) >= 1 {
argFilename := fmt.Sprintf("%v", args[0])
if len(argFilename) > 0 {
filename = strings.TrimSpace(argFilename)
}
}
if len(args) >= 2 {
argFieldname := fmt.Sprintf("%v", args[1])
if len(argFieldname) > 0 {
fieldname = strings.TrimSpace(argFieldname)
}
}
if len(args) >= 3 {
argSkipFileNumbering := reflect.ValueOf(args[2])
if argSkipFileNumbering.Type().Name() == "bool" {
skipFileNumbering = argSkipFileNumbering.Interface().(bool)
}
}
if len(args) >= 4 {
argFileType := fmt.Sprintf("%v", args[3])
if len(argFileType) > 0 {
fileType = strings.TrimSpace(argFileType)
}
if fileType == "" {
s.Errors = append(s.Errors, errors.New("the fifth SendFile method argument for MIME type cannot be an empty string"))
return s
}
}
if (fieldname == "file" && !skipFileNumbering) || fieldname == "" {
fieldname = "file" + strconv.Itoa(len(s.FileData)+1)
}
switch v := reflect.ValueOf(file); v.Kind() {
case reflect.String:
pathToFile, err := filepath.Abs(v.String())
if err != nil {
s.Errors = append(s.Errors, err)
return s
}
if filename == "" {
filename = filepath.Base(pathToFile)
}
data, err := ioutil.ReadFile(v.String())
if err != nil {
s.Errors = append(s.Errors, err)
return s
}
s.FileData = append(s.FileData, File{
Filename: filename,
Fieldname: fieldname,
MimeType: fileType,
Data: data,
})
case reflect.Slice:
slice := makeSliceOfReflectValue(v)
if filename == "" {
filename = "filename"
}
f := File{
Filename: filename,
Fieldname: fieldname,
MimeType: fileType,
Data: make([]byte, len(slice)),
}
for i := range slice {
f.Data[i] = slice[i].(byte)
}
s.FileData = append(s.FileData, f)
case reflect.Ptr:
if len(args) == 1 {
return s.SendFile(v.Elem().Interface(), args[0])
}
if len(args) == 2 {
return s.SendFile(v.Elem().Interface(), args[0], args[1])
}
if len(args) == 3 {
return s.SendFile(v.Elem().Interface(), args[0], args[1], args[2])
}
if len(args) == 4 {
return s.SendFile(v.Elem().Interface(), args[0], args[1], args[2], args[3])
}
return s.SendFile(v.Elem().Interface())