-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathworker.go
54 lines (43 loc) · 1.01 KB
/
worker.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
package scrapegoat
import "net/http"
type worker struct {
spider *Spider
client *http.Client
quit chan struct{}
}
func (s *Spider) newWorker() *worker {
worker := &worker{}
worker.spider = s
worker.client = &http.Client{}
worker.quit = make(chan struct{}, 1)
return worker
}
func (w *worker) start() {
go func() {
for {
select {
case urlReq := <-w.spider.urlQueue:
w.spider.logger.Printf("Sending request to %s\n", urlReq.url)
resp, err := urlReq.send(w.client)
w.spider.logger.Printf("Received response from %s in %v\n", urlReq.url, resp.Elapsed)
if err != nil {
// log the error
w.spider.logger.Printf("Received error %s", err)
// and continue
break
}
item := w.spider.NewItemFunc()
w.spider.logger.Println("Parsing item")
item.Parse(resp, urlReq.ctx)
w.spider.logger.Printf("Parsed item %+v\n", item)
resp.Item = item
w.spider.results <- resp
case <-w.quit:
return
}
}
}()
}
func (w *worker) stop() {
w.quit <- struct{}{}
}