forked from bitholic/gorequests
/
req.go
288 lines (246 loc) · 6.26 KB
/
req.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
package gorequests
import (
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"strings"
"time"
)
// ----- get params
// Context request context.Context
func (r *Request) Context() context.Context {
if r.context != nil {
return r.context
}
return context.TODO()
}
// Timeout request timeout
func (r *Request) Timeout() time.Duration {
return r.timeout
}
// URL request url
func (r *Request) URL() string {
return r.url
}
// RequestFullURL request full url, contain query param
func (r *Request) RequestFullURL() string {
r.lock.RLock()
defer r.lock.RUnlock()
return r.parseRequestURL()
}
func (r *Request) getStrCtx(key string) string {
ctx := r.Context()
if ctx == nil {
return ""
}
v := ctx.Value(key)
switch v := v.(type) {
case string:
return v
case *string:
return *v
}
return ""
}
// LogMessage unit test only
func (r *Request) LogMessage() *LogMessage {
return r.log
}
// Method request method
func (r *Request) Method() string {
return r.method
}
// RequestHeader request header
func (r *Request) RequestHeader() http.Header {
return r.header
}
// ----- set params
func (r *Request) SetFullUrl(url string) {
r.lock.RLock()
defer r.lock.RUnlock()
if url == "" {
return
}
r.fullUrl = url
}
// WithContext setup request context.Context
func (r *Request) WithContext(ctx context.Context) *Request {
return r.configParamFactor(func(r *Request) {
r.context = ctx
})
}
// WithTimeout setup request timeout
func (r *Request) WithTimeout(timeout time.Duration) *Request {
return r.configParamFactor(func(r *Request) {
r.timeout = timeout
})
}
// WithIgnoreSSL ignore ssl verify
func (r *Request) WithIgnoreSSL(ignore bool) *Request {
return r.configParamFactor(func(r *Request) {
r.isIgnoreSSL = ignore
})
}
// WithHeader set one header k-v map
func (r *Request) WithHeader(k, v string) *Request {
return r.configParamFactor(func(r *Request) {
r.configHeader(k, v)
})
}
// WithHeaders set multi header k-v map
func (r *Request) WithHeaders(kv map[string]string) *Request {
return r.configParamFactor(func(r *Request) {
for k, v := range kv {
r.configHeader(k, v)
}
})
}
// WithHeaders set multi header k-v map
func (r *Request) configHeader(k, v string) {
//if strings.ToLower(k) == "user-agent" {
r.header.Add(k, v)
//} else {
// r.header.Add(k, v)
//}
}
// WithRedirect set allow or not-allow redirect with Location header
func (r *Request) WithRedirect(b bool) *Request {
return r.configParamFactor(func(r *Request) {
r.isNoRedirect = !b
})
}
// WithQuery set one query k-v map
func (r *Request) WithQuery(k, v string) *Request {
return r.configParamFactor(func(r *Request) {
r.querys[k] = append(r.querys[k], v)
})
}
// WithQuerys set multi query k-v map
func (r *Request) WithQuerys(kv map[string]string) *Request {
return r.configParamFactor(func(r *Request) {
for k, v := range kv {
r.querys[k] = append(r.querys[k], v)
}
})
}
// WithQueryStruct set multi query k-v map
func (r *Request) WithQueryStruct(v interface{}) *Request {
return r.configParamFactor(func(r *Request) {
kv, err := queryToMap(v)
if err != nil {
r.err = err
return
}
for k, v := range kv {
r.querys[k] = append(r.querys[k], v...)
}
})
}
// WithBody set request body, support: io.Reader, []byte, string, interface{}(as json format)
func (r *Request) WithBody(body interface{}) *Request {
return r.configParamFactor(func(r *Request) {
r.rawBody, r.body, r.err = toBody(body)
})
}
// WithJSON set body same as WithBody, and set Content-Type to application/json
func (r *Request) WithJSON(body interface{}) *Request {
return r.configParamFactor(func(r *Request) {
r.rawBody, r.body, r.err = toBody(body)
if r.err != nil {
return
}
r.header.Set("Content-Type", "application/json")
})
}
// WithForm set body and set Content-Type to multiform
func (r *Request) WithForm(body map[string]string) *Request {
return r.configParamFactor(func(r *Request) {
buf := bytes.Buffer{}
f := multipart.NewWriter(&buf)
for k, v := range body {
if err := f.WriteField(k, v); err != nil {
r.err = err
return
}
}
r.rawBody, r.body = buf.Bytes(), strings.NewReader(buf.String())
r.header.Set("Content-Type", f.FormDataContentType())
})
}
// WithFormURLEncoded set body and set Content-Type to application/x-www-form-urlencoded
func (r *Request) WithFormURLEncoded(body map[string]string) *Request {
return r.configParamFactor(func(r *Request) {
u := url.Values{}
for k, v := range body {
u.Add(k, v)
}
r.rawBody, r.body = []byte(u.Encode()), strings.NewReader(u.Encode())
r.header.Set("Content-Type", "application/x-www-form-urlencoded")
})
}
// WithFile set file to body and set some multi-form k-v map
func (r *Request) WithFile(filename string, file io.Reader, fileKey string, params map[string]string) *Request {
return r.configParamFactor(func(r *Request) {
contentType, bod, err := newFileUploadRequest(params, fileKey, filename, file)
if err != nil {
r.err = err
return
}
r.rawBody, r.body = nil, bod
r.header.Set("Content-Type", contentType)
})
}
// WithURLCookie set cookie of uri
func (r *Request) WithURLCookie(uri string) *Request {
return r.configParamFactor(func(r *Request) {
if r.persistentJar == nil {
return
}
uriParse, err := url.Parse(uri)
if err != nil {
r.err = err
return
}
cookies := []string{}
for _, v := range r.persistentJar.Cookies(uriParse) {
cookies = append(cookies, v.Name+"="+v.Value)
}
if len(cookies) > 0 {
r.header.Add("cookie", strings.Join(cookies, "; ")) // use add not set
}
})
}
func (r *Request) WithLogProducer(producer LogProducer) *Request {
return r.configParamFactor(func(r *Request) {
r.logProducer = producer
})
}
func (r *Request) WithLogId(logId string) *Request {
return r.configParamFactor(func(r *Request) {
r.logId = logId
})
}
// WithLogger set logger
func (r *Request) WithLogger(logger Logger) *Request {
return r.configParamFactor(func(r *Request) {
r.logger = logger
})
}
// WithHeader set one header k-v map
func (r *Request) configParamFactor(f func(*Request)) *Request {
r.lock.Lock()
defer r.lock.Unlock()
if r.isRequest {
r.SetError(fmt.Errorf("request %s %s alreday sended, cannot set request params", r.method, r.cachedurl))
return r
}
if r.err != nil {
return r
}
f(r)
return r
}