-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.go
66 lines (59 loc) · 1.37 KB
/
context.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
package crawler
// Context 爬虫执行上下文
type Context struct {
Engine *CrawlEngine
Crawler *Crawler
Settings *Settings
Depth int32
LastRequest *Request
LastResponse *Response
}
func (ctx *Context) copy() *Context {
return &Context{
Engine: ctx.Engine,
Crawler: ctx.Crawler,
Settings: ctx.Settings,
Depth: ctx.Depth,
LastRequest: ctx.LastRequest,
LastResponse: ctx.LastResponse,
}
}
// AddRequest 添加请求
func (ctx *Context) AddRequest(req *Request) {
// fmt.Println("add: ", req)
if req == nil {
return
}
context := ctx.copy()
context.Depth++
if context.LastResponse != nil && req.Headers.Get("Referer") == "" && req.Headers.Get("referer") == "" {
req.Headers.Set("Referer", context.LastResponse.URL)
}
context.LastRequest = req
req.context = context
ctx.Engine.RequestQueue <- req
}
// AddItem 处理item
func (ctx *Context) AddItem(item interface{}) {
// i :=1;
// fmt.Println(item)
ctx.Engine.ItemQueue <- &itemWrapper{item: item, context: ctx}
}
// Emit 提交Request或item
func (ctx *Context) Emit(item interface{}) {
// i :=1;
switch item.(type) {
case *Request:
ctx.AddRequest(item.(*Request))
break
case Request:
request := item.(Request)
ctx.AddRequest(&request)
break
default:
ctx.AddItem(item)
}
}
func (ctx *Context) retry(req *Request) {
ctx.Engine.RequestQueue <- req
}