-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.go
82 lines (63 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
79
80
81
82
package main
import (
"fmt"
"net/http"
"strings"
"time"
"github.com/xperimental/linky/html"
)
var clientTimeout = 60 * time.Second
type worker struct {
client *http.Client
locations <-chan location
updates chan<- update
userAgent string
}
func newWorker(locations <-chan location, updates chan<- update, userAgent string) *worker {
w := &worker{
client: &http.Client{
Timeout: clientTimeout,
},
locations: locations,
updates: updates,
userAgent: userAgent,
}
go w.loop()
return w
}
func (w *worker) loop() {
for l := range w.locations {
result := w.fetchURL(l)
go func() {
w.updates <- result
}()
}
}
func (w *worker) fetchURL(location location) (result update) {
result.Location = location
start := time.Now()
req, err := http.NewRequest(http.MethodGet, location.URL, nil)
if err != nil {
result.Error = fmt.Errorf("can not create request: %s", err)
return
}
if w.userAgent != "" {
req.Header.Set("User-Agent", w.userAgent)
}
res, err := w.client.Do(req)
result.ResponseTime = time.Since(start)
if err != nil {
result.Error = err
return
}
defer res.Body.Close()
result.Status = res.StatusCode
if res.StatusCode < http.StatusOK || res.StatusCode >= 300 {
return
}
result.ContentType = res.Header.Get("Content-Type")
if strings.HasPrefix(result.ContentType, "text/html") {
result.Links = html.ParseLinks(res.Body)
}
return result
}