-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrawlerjob.go
84 lines (67 loc) · 1.32 KB
/
crawlerjob.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
package crawler
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
"sync"
"github.com/phantom-atom/crawler/parser"
)
var (
//bytes.Buffer对象池
bufPool = &sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
)
type crawlerJob struct {
e *Engine
r *parser.Request
}
func (c *crawlerJob) Execute() error {
if c.r.WaitGroup != nil {
defer c.r.WaitGroup.Done()
}
buf, err := c.get()
if err != nil {
return err
}
result, err := c.r.Parser.Parse(c.r, buf)
bufPool.Put(buf)
if err != nil {
return err
}
if result != nil {
requests := result.Requests()
for _, req := range requests {
c.e.Process(req)
}
}
return nil
}
func (c *crawlerJob) get() (*bytes.Buffer, error) {
resp, err := http.Get(c.r.URL.String())
if resp != nil {
defer resp.Body.Close()
}
if err != nil {
return nil, err
}
//如果请求的状态码不是OK,那么需要将resp.Body
//清空,以便复用连接,并返回错误信息
if resp.StatusCode != http.StatusOK {
io.Copy(ioutil.Discard, resp.Body)
return nil, fmt.Errorf("request: url=%s, status_code=%d", c.r.URL.String(), resp.StatusCode)
}
//从对象池中获取一个Buffer
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
_, err = io.Copy(buf, resp.Body)
if err != nil {
bufPool.Put(buf)
return nil, err
}
return buf, nil
}