forked from parnurzeal/gorequest
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
461 lines (436 loc) · 13.5 KB
/
main.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
// Package gorequest inspired by Nodejs SuperAgent provides easy-way to write http client
package gorequest
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net"
"net/http"
"net/url"
"reflect"
"strings"
"time"
)
type Request *http.Request
type Response *http.Response
// A SuperAgent is a object storing all request data for client.
type SuperAgent struct {
Url string
Method string
Header map[string]string
TargetType string
ForceType string
Data map[string]interface{}
FormData url.Values
QueryData url.Values
Client *http.Client
Transport *http.Transport
Errors []error
}
// Used to create a new SuperAgent object.
func New() *SuperAgent {
s := &SuperAgent{
TargetType: "json",
Data: make(map[string]interface{}),
Header: make(map[string]string),
FormData: url.Values{},
QueryData: url.Values{},
Client: &http.Client{},
Transport: &http.Transport{},
Errors: nil,
}
return s
}
// Clear SuperAgent data for another new request.
func (s *SuperAgent) ClearSuperAgent() {
s.Url = ""
s.Method = ""
s.Header = make(map[string]string)
s.Data = make(map[string]interface{})
s.FormData = url.Values{}
s.QueryData = url.Values{}
s.ForceType = ""
s.TargetType = "json"
s.Errors = nil
}
func (s *SuperAgent) Get(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = "GET"
s.Url = targetUrl
s.Errors = nil
return s
}
// TODO: add test for Post
func (s *SuperAgent) Post(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = "POST"
s.Url = targetUrl
s.Errors = nil
return s
}
// TODO: testing for Head func
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
}
// Set is used for setting header fields.
// Example. To set `Accept` as `application/json`
//
// gorequest.New().
// Post("/gamelist").
// Set("Accept", "application/json").
// End()
// TODO: make Set be able to get multiple fields
func (s *SuperAgent) Set(param string, value string) *SuperAgent {
s.Header[param] = value
return s
}
var Types = map[string]string{
"html": "text/html",
"json": "application/json",
"xml": "application/xml",
"urlencoded": "application/x-www-form-urlencoded",
"form": "application/x-www-form-urlencoded",
"form-data": "application/x-www-form-urlencoded",
}
// 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"
// "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, errors.New("Type func: incorrect type \""+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()
//
// TODO: check error
func (s *SuperAgent) Query(content string) *SuperAgent {
var val map[string]string
if err := json.Unmarshal([]byte(content), &val); err == nil {
for k, v := range val {
s.QueryData.Add(k, v)
}
} else {
if queryVal, err := url.ParseQuery(content); err == nil {
for k, _ := range queryVal {
s.QueryData.Add(k, queryVal.Get(k))
}
} else {
s.Errors = append(s.Errors, err)
}
// TODO: need to check correct format of 'field=val&field=val&...'
}
return s
}
// TODO-1: Add docs for Timeout
// TODO-2: a test for Timeout, check time and slow server
func (s *SuperAgent) Timeout(timeout time.Duration) *SuperAgent {
s.Transport.Dial = func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
}
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.Transport.Proxy = nil
} else {
s.Transport.Proxy = http.ProxyURL(parsedProxyUrl)
}
return s
}
func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) error) *SuperAgent {
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()
//
// TODO: check error from form and add normal text mode or other mode to Send func
func (s *SuperAgent) Send(content interface{}) *SuperAgent {
switch v := reflect.ValueOf(content); v.Kind() {
case reflect.String:
s.SendString(v.String())
case reflect.Struct:
s.sendStruct(v.Interface())
default:
// TODO: leave default for handling other types in the future such as number, byte, etc...
}
return s
}
// sendStruct (similar to SendString) returns SuperAgent's itself for any next chain and takes content interface{} as a parameter.
// Its duty is to transfrom 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{}
if err := json.Unmarshal(marshalContent, &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 {
var val map[string]interface{}
// check if it is json format
if err := json.Unmarshal([]byte(content), &val); err == nil {
for k, v := range val {
s.Data[k] = v
}
} else if formVal, err := url.ParseQuery(content); err == nil {
for k, _ := range formVal {
// make it array if already have key
if val, ok := s.Data[k]; ok {
var strArray []string
strArray = append(strArray, formVal.Get(k))
// 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] = formVal.Get(k)
}
}
s.TargetType = "form"
} else {
// need to add text mode or other format body request to this func
}
return s
}
func changeMapToURLValues(data map[string]interface{}) url.Values {
var newUrlValues = url.Values{}
for k, v := range data {
switch val := v.(type) {
case string:
newUrlValues.Add(k, string(val))
case []string:
for _, element := range val {
newUrlValues.Add(k, element)
}
}
}
return newUrlValues
}
// End is the most important function that you need to call when ending the chain. The request won't proceed without calling it.
// End function returns Response which matchs the structure of Response type in Golang's http package (but without Body data). The body data itself returns as a string in a 2nd return value.
// Lastly but worht noticing, error array (NOTE: not just single error value) is returned as a 3rd value and nil otherwise.
//
// For example:
//
// resp, body, errs := gorequest.New().Get("http://www.google.com").End()
// if( errs != nil){
// fmt.Pritnln(errs)
// }
// fmt.Println(resp, body)
//
// Moreover, End function also supports callback which you can put as a parameter.
// This extends the flexibility and makes GoRequest fun and clean! You can use GoRequest in whatever style you love!
//
// For example:
//
// func printBody(resp gorequest.Response, body string, errs []error){
// fmt.Println(resp.Status)
// }
// gorequest.New().Get("http://www..google.com").End(printBody)
//
func (s *SuperAgent) End(callback ...func(response Response, body string, errs []error)) (Response, string, []error) {
var (
req *http.Request
err error
resp Response
)
// check whether there is an error. if yes, return all errors
if len(s.Errors) != 0 {
return nil, "", s.Errors
}
// check if there is forced type
if s.ForceType == "json" {
s.TargetType = "json"
} else if s.ForceType == "form" {
s.TargetType = "form"
}
if s.Method == "POST" || s.Method == "PUT" {
if s.TargetType == "json" {
contentJson, _ := json.Marshal(s.Data)
contentReader := bytes.NewReader(contentJson)
req, err = http.NewRequest(s.Method, s.Url, contentReader)
req.Header.Set("Content-Type", "application/json")
} else if s.TargetType == "form" {
formData := changeMapToURLValues(s.Data)
req, err = http.NewRequest(s.Method, s.Url, strings.NewReader(formData.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
}
} else if s.Method == "GET" {
req, err = http.NewRequest(s.Method, s.Url, nil)
} else if s.Method == "HEAD" {
req, err = http.NewRequest(s.Method, s.Url, nil)
} else if s.Method == "DELETE" {
req, err = http.NewRequest(s.Method, s.Url, nil)
}
for k, v := range s.Header {
req.Header.Set(k, v)
}
// Add all querystring from Query func
q := req.URL.Query()
for k, v := range s.QueryData {
for _, vv := range v {
q.Add(k, vv)
}
}
req.URL.RawQuery = q.Encode()
// Set Transport
s.Client.Transport = s.Transport
// Send request
resp, err = s.Client.Do(req)
if err != nil {
s.Errors = append(s.Errors, err)
return nil, "", s.Errors
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
bodyCallback := body
// deep copy response to give it to both return and callback func
respCallback := *resp
if len(callback) != 0 {
callback[0](&respCallback, string(bodyCallback), s.Errors)
}
return resp, string(body), nil
}