-
Notifications
You must be signed in to change notification settings - Fork 1
/
request.go
320 lines (283 loc) · 8.51 KB
/
request.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
// MIT License
// Copyright (c) 2023 wetrycode
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package tegenaria
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/url"
"strings"
"sync"
"time"
jsoniter "github.com/json-iterator/go"
"github.com/mitchellh/mapstructure"
"github.com/sirupsen/logrus"
)
// Proxy 代理数据结构
type Proxy struct {
// ProxyUrl 代理链接
ProxyUrl string
}
// Request 请求对象的结构
type Request struct {
// Url 请求Url
Url string `json:"url"`
// Headers 请求头
Headers map[string]string `json:"headers"`
// Method 请求方式
Method RequestMethod `json:"method"`
// Body 请求body
body []byte `json:"-"`
// Params 请求url的参数
Params map[string]string `json:"params"`
// Proxy 代理实例
Proxy *Proxy `json:"-"`
// Cookies 请求携带的cookies
Cookies map[string]string `json:"cookies"`
// Meta 请求携带的额外的信息
Meta map[string]interface{} `json:"meta"`
// AllowRedirects 是否允许跳转默认允许
AllowRedirects bool `json:"allowRedirects"`
// MaxRedirects 最大的跳转次数
MaxRedirects int `json:"maxRedirects"`
// Parser 该请求绑定的响应解析函数,必须是一个spider实例
Parser string `json:"parser"`
// MaxConnsPerHost 单个域名最大的连接数
MaxConnsPerHost int `json:"maxConnsPerHost"`
// BodyReader 用于读取body
bodyReader io.Reader `json:"-"`
// AllowStatusCode 允许的状态码
AllowStatusCode []uint64 `json:"allowStatusCode"`
// Timeout 请求超时时间
Timeout time.Duration `json:"timeout"`
// DoNotFilter
DoNotFilter bool
}
// Option NewRequest 可选参数
type RequestOption func(r *Request)
// Parser 响应解析函数结构
type Parser func(resp *Context, req chan<- *Context) error
// bufferPool buffer 对象内存池
var bufferPool *sync.Pool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(make([]byte, 8192))
// return new(bytes.Buffer)
},
}
// reqLog request logger
var reqLog *logrus.Entry = GetLogger("request")
// RequestWithRequestBody 传入请求体到request
func RequestWithRequestBody(body map[string]interface{}) RequestOption {
return func(r *Request) {
var err error
buf, err := jsoniter.Marshal(body)
r.bodyReader = bytes.NewBuffer(buf)
if err != nil {
reqLog.Errorf("set request body err %s", err.Error())
panic(fmt.Sprintf("set request body err %s", err.Error()))
}
}
}
// RequestWithRequestBytesBody request绑定bytes body
func RequestWithRequestBytesBody(body []byte) RequestOption {
return func(r *Request) {
r.bodyReader = bytes.NewReader(body)
}
}
// RequestWithRequestParams 设置请求的url参数
func RequestWithRequestParams(params map[string]string) RequestOption {
return func(r *Request) {
r.Params = params
}
}
// RequestWithRequestProxy 设置代理
func RequestWithRequestProxy(proxy Proxy) RequestOption {
return func(r *Request) {
r.Proxy = &proxy
}
}
// RequestWithRequestHeader 设置请求头
func RequestWithRequestHeader(headers map[string]string) RequestOption {
return func(r *Request) {
r.Headers = headers
}
}
// RequestWithRequestCookies 设置cookie
func RequestWithRequestCookies(cookies map[string]string) RequestOption {
return func(r *Request) {
r.Cookies = cookies
}
}
// RequestWithRequestMeta 设置 meta
func RequestWithRequestMeta(meta map[string]interface{}) RequestOption {
return func(r *Request) {
r.Meta = meta
}
}
// RequestWithAllowRedirects 设置是否允许跳转
// 如果不允许则MaxRedirects=0
func RequestWithAllowRedirects(allowRedirects bool) RequestOption {
return func(r *Request) {
r.AllowRedirects = allowRedirects
if !allowRedirects {
r.MaxRedirects = 0
}
}
}
// RequestWithMaxRedirects 设置最大的跳转次数
// 若maxRedirects <= 0则认为不允许跳转AllowRedirects = false
func RequestWithMaxRedirects(maxRedirects int) RequestOption {
return func(r *Request) {
if maxRedirects <= 0 {
r.AllowRedirects = false
r.MaxRedirects = 0
} else {
r.MaxRedirects = maxRedirects
r.AllowRedirects = true
}
}
}
// RequestWithMaxConnsPerHost 设置MaxConnsPerHost
func RequestWithMaxConnsPerHost(maxConnsPerHost int) RequestOption {
return func(r *Request) {
r.MaxConnsPerHost = maxConnsPerHost
}
}
// RequestWithAllowedStatusCode 设置AllowStatusCode
func RequestWithAllowedStatusCode(allowStatusCode []uint64) RequestOption {
return func(r *Request) {
r.AllowStatusCode = allowStatusCode
}
}
// RequestWithParser 设置Parser
func RequestWithParser(parser Parser) RequestOption {
return func(r *Request) {
r.Parser = GetFunctionName(parser)
}
}
// RequestWithDoNotFilter 设置当前请求是否进行过滤处理,
// true则认为该条请求无需进入去重流程,默认值为false
func RequestWithDoNotFilter(doNotFilter bool) RequestOption {
return func(r *Request) {
r.DoNotFilter = doNotFilter
}
}
// RequestWithTimeout 设置请求超时时间
// 若timeout<=0则认为没有超时时间
func RequestWithTimeout(timeout time.Duration) RequestOption {
return func(r *Request) {
r.Timeout = timeout
}
}
// RequestWithPostForm set application/x-www-form-urlencoded
// request body reader
func RequestWithPostForm(payload url.Values) RequestOption {
return func(r *Request) {
r.bodyReader = strings.NewReader(payload.Encode())
}
}
// RequestWithBodyReader set request body io.Reader
func RequestWithBodyReader(body io.Reader) RequestOption {
return func(r *Request) {
r.bodyReader = body
}
}
// updateQueryParams 将Params配置到url
func (r *Request) updateQueryParams() {
if len(r.Params) != 0 {
u, err := url.Parse(r.Url)
if err != nil {
panic(fmt.Sprintf("set request query params err %s", err.Error()))
}
q := u.Query()
for key, value := range r.Params {
q.Set(key, value)
}
u.RawQuery = q.Encode()
r.Url = u.String()
}
}
// 请注意parser函数必须是某一个spiderinterface实例的解析函数
// 否则无法正常调用该解析函数
func NewRequest(url string, method RequestMethod, parser Parser, opts ...RequestOption) *Request {
request := &Request{
Url: url,
Method: method,
Parser: GetFunctionName(parser),
Headers: make(map[string]string),
Meta: make(map[string]interface{}),
Cookies: make(map[string]string),
DoNotFilter: false,
AllowRedirects: true,
MaxRedirects: 3,
MaxConnsPerHost: 128,
AllowStatusCode: make([]uint64, 0),
Timeout: -1 * time.Second,
bodyReader: nil,
}
for _, o := range opts {
o(request)
}
request.updateQueryParams()
return request
}
// ToMap 将request对象转为map
func (r *Request) ToMap() (map[string]interface{}, error) {
if r.bodyReader != nil {
body, err := io.ReadAll(r.bodyReader)
if err != nil {
return nil, err
}
r.body = body
}
b, err := json.Marshal(r)
if err != nil {
return nil, err
}
var m map[string]interface{}
err = json.Unmarshal(b, &m)
m["body"] = r.body
return m, err
}
// RequestFromMap 从map创建requests
func RequestFromMap(src map[string]interface{}, opts ...RequestOption) *Request {
request := &Request{
Url: "",
Method: "",
Parser: "",
Headers: make(map[string]string),
Meta: make(map[string]interface{}),
DoNotFilter: false,
AllowRedirects: true,
MaxRedirects: 3,
AllowStatusCode: make([]uint64, 0),
Timeout: -1 * time.Second,
bodyReader: nil,
body: nil,
}
err := mapstructure.Decode(src, request)
if err != nil {
panic(err.Error())
}
for _, o := range opts {
o(request)
}
request.updateQueryParams()
return request
}