-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
78 lines (62 loc) · 1.39 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main
import (
"context"
"encoding/json"
"time"
"github.com/chromedp/chromedp"
)
type JobConfig struct {
Collection string `json:"name"`
Url string `json:"url"`
Fields []JobConfigField `json:"fields"`
Id string `json:"id,omitempty"`
}
type JobConfigField struct {
Name string `json:"name"`
Selector string `json:"selector"`
Attr string `json:"attr,omitempty"`
Children []JobConfigField `json:"children,omitempty"`
Regex string `json:"regex,omitempty"`
}
func worker(rawConfig []byte, ctx context.Context, bb *Busyboi) {
var conf JobConfig
err := json.Unmarshal(rawConfig, &conf)
if err != nil {
// Raport error
return
}
cache := bb.cache.Has(conf.Url)
// Cache hit!
if cache != nil {
// fmt.Println(bb.cache.table)
return
}
// Re-queue job is site is unreachable
ok := canReach(conf.Url)
if !ok {
bb.mq.RabbitMqAddMessages(conf)
return
}
// Check if we can crawl
ok = robots(conf.Url)
if !ok {
return
}
c, cancel := chromedp.NewContext(ctx)
defer cancel()
var DOM string
// run task list
err = chromedp.Run(c,
chromedp.Navigate(conf.Url),
chromedp.InnerHTML("html", &DOM),
)
if err != nil {
return
}
data := parse(conf.Fields, DOM, "")
bb.cache.AddOrUpdate(Bucket{
Url: conf.Url,
Refreshed: time.Now(),
Data: data,
})
}