-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkscraper.go
252 lines (216 loc) · 4.88 KB
/
linkscraper.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
package linkscraper
import (
"fmt"
"golang.org/x/net/html"
"log"
"net"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
httpTimeout = time.Second * 3
goroutines = 20
chanCapacity = 10 * 1000
)
var (
NonExistingPage = &Page{
Title: "404 NOT FOUND",
}
)
type Page struct {
URL *url.URL `json:"-"`
Title string
Links []*Link
}
type Link struct {
Title string
Page *Page `json:"-"`
TargetPage *Page `json:"-"`
Target string
TargetURL *url.URL `json:"-"`
Internal bool
Anchor bool
Malformed bool
Dead bool
}
type LinkChecker struct {
client *http.Client
startURL *url.URL
visited map[string]*Page
visitLock sync.RWMutex
queue chan *Link
waitGroup sync.WaitGroup
StartPage *Page
}
func New(startURL string) (checker *LinkChecker, err error) {
start, err := url.Parse(startURL)
if err != nil {
return nil, fmt.Errorf("error parsing start URL: %v", err)
}
client := &http.Client{
Timeout: httpTimeout,
}
resp, err := client.Get(startURL)
if isTimeout(err) {
return nil, fmt.Errorf("timeout while getting start URL: %v", err)
} else if err != nil {
return nil, fmt.Errorf("error getting start URL: %v", err)
}
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return nil, fmt.Errorf("unexpected status code for start URL: %d", resp.StatusCode)
}
return &LinkChecker{
client: client,
startURL: start,
visited: make(map[string]*Page),
queue: make(chan *Link, chanCapacity),
}, nil
}
func (l *LinkChecker) Visited() map[string]*Page {
return l.visited
}
func (l *LinkChecker) Start() (err error) {
l.waitGroup.Add(1)
l.queue <- &Link{
Dead: false,
Target: l.startURL.String(),
TargetURL: l.startURL,
Malformed: false,
Internal: true,
Anchor: false,
}
for i := 0; i < goroutines; i++ {
go l.runRoutine()
}
l.waitGroup.Wait()
close(l.queue)
l.StartPage = l.visited[l.startURL.String()]
return nil
}
func (l *LinkChecker) runRoutine() {
for {
link, ok := <-l.queue
if !ok {
return // Were done!
}
l.processLink(link)
l.waitGroup.Done()
}
}
func (l *LinkChecker) processLink(link *Link) {
l.visitLock.RLock()
page := l.visited[link.TargetURL.String()]
l.visitLock.RUnlock()
if page != nil {
link.TargetPage = page
link.Dead = false
return
}
statusCode, page, err := l.visitPage(link.TargetURL)
if err != nil {
log.Printf("Error visiting page: %s |> %v", link.Target, err)
return
}
l.visitLock.Lock()
l.visited[link.TargetURL.String()] = page
l.visitLock.Unlock()
link.TargetPage = page
link.Dead = statusCode < 200 || statusCode > 299
}
// visitPage visits a link and gathers statistics for it (recursively)
func (l *LinkChecker) visitPage(curURL *url.URL) (statusCode int, page *Page, err error) {
//log.Printf("Visiting URL: %s", curURL.String())
resp, err := l.client.Get(curURL.String())
if isTimeout(err) {
return 0, NonExistingPage, nil
}
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
return resp.StatusCode, NonExistingPage, nil
}
page = &Page{
URL: curURL,
}
tokenizer := html.NewTokenizer(resp.Body)
prevStartToken := tokenizer.Token()
var lastLink *Link
for {
tokenType := tokenizer.Next()
token := tokenizer.Token()
switch tokenType {
case html.ErrorToken:
return //were done
case html.StartTagToken:
prevStartToken = token
switch strings.ToLower(token.Data) {
case "a":
lastLink = l.processAnchor(page, token)
if lastLink != nil {
page.Links = append(page.Links, lastLink)
}
}
case html.TextToken:
switch strings.ToLower(prevStartToken.Data) {
case "title":
page.Title += strings.TrimSpace(token.String())
case "a":
if lastLink != nil {
lastLink.Title += strings.TrimSpace(token.String())
}
}
}
}
return resp.StatusCode, page, nil
}
func (l *LinkChecker) processAnchor(page *Page, anchor html.Token) *Link {
for i := range anchor.Attr {
if strings.ToLower(anchor.Attr[i].Key) != "href" {
continue
}
link := &Link{
Page: page,
Target: anchor.Attr[i].Val,
}
if strings.TrimSpace(anchor.Attr[i].Val) == "" {
link.Malformed = true
return link
}
if strings.HasPrefix(strings.TrimSpace(anchor.Attr[i].Val), "#") {
link.Internal = true
link.Anchor = true
return link
}
var err error
link.TargetURL, err = url.Parse(anchor.Attr[i].Val)
if err != nil {
link.Malformed = true
log.Printf("Found an unparsable link: %s (%v)", anchor.Attr[i].Val, err)
return link
}
link.Internal = l.isInternal(link.TargetURL)
if link.Internal {
l.waitGroup.Add(1)
l.queue <- link
}
return link
}
return nil
}
func (l *LinkChecker) isInternal(URL *url.URL) bool {
return l.startURL.Host == URL.Host
}
func isTimeout(err error) bool {
if err == nil {
return false
}
if netErr, ok := err.(net.Error); ok {
return netErr.Timeout()
}
return false
}