forked from parnurzeal/gorequest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
260 lines (243 loc) · 6.37 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
// Package gorequest inspired by Nodejs SuperAgent provides easy-way to write http client
package gorequest
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strings"
)
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
}
// 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{},
}
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"
}
func (s *SuperAgent) Get(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = "GET"
s.Url = targetUrl
return s
}
func (s *SuperAgent) Post(targetUrl string) *SuperAgent {
s.ClearSuperAgent()
s.Method = "POST"
s.Url = targetUrl
return s
}
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",
}
func (s *SuperAgent) Type(typeStr string) *SuperAgent {
if _, ok := Types[typeStr]; ok {
s.ForceType = typeStr
}
return s
}
// Query method accepts ether 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 {
queryVal, _ := url.ParseQuery(content)
for k, _ := range queryVal {
s.QueryData.Add(k, queryVal.Get(k))
}
// TODO: need to check correct format of 'field=val&field=val&...'
}
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
}
func (s *SuperAgent) Send(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 {
formVal, _ := url.ParseQuery(content)
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"
}
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
}
func (s *SuperAgent) End(callback ...func(response Response, body string)) (Response, string, error) {
var (
req *http.Request
err error
resp Response
)
// 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" {
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)
}
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()
// Send request
fmt.Println(req.URL)
resp, err = s.Client.Do(req)
if err != nil {
return nil, "", err
}
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))
}
return resp, string(body), nil
}
func main() {
New().Post("http://requestb.in/1f7ur5s1").
Send(`nickname=a`).
Set("Accept", "application/json").
End(func(response Response, body string) {
fmt.Println(response)
})
}