-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcrawler.go
177 lines (148 loc) · 3.32 KB
/
crawler.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"strings"
"time"
"golang.org/x/net/html"
)
// PrettyPrint takes a site map and prints it as json
func PrettyPrint(site map[string][]*url.URL) {
type SiteMapItem struct {
URL string `json:"url"`
Links []string `json:"links"`
}
fmt.Print("[")
first := true
for k, v := range site {
links := []string{}
for _, u := range v {
links = append(links, u.String())
}
item := SiteMapItem{URL: k, Links: links}
jsonStr, err := json.Marshal(item)
if err != nil {
log.Printf("Error pretty printing: %v", err)
return
}
if !first {
fmt.Print(",")
}
fmt.Print(string(jsonStr))
first = false
}
fmt.Print("]")
}
// ParseHTML takes a html body and returns a list of referred URLs
func ParseHTML(body string) []*url.URL {
r := strings.NewReader(body)
tokenizer := html.NewTokenizer(r)
result := []*url.URL{}
for {
tt := tokenizer.Next()
if tt == html.ErrorToken {
break
}
if tt == html.StartTagToken {
t := tokenizer.Token()
if t.Data == "a" {
for _, attr := range t.Attr {
if attr.Key == "href" {
u, err := url.Parse(attr.Val)
if err != nil {
log.Printf("Error parsing url %v: %v", attr.Val, err)
continue
}
result = append(result, u)
}
}
}
}
}
return result
}
// FilterByHostname takes a list of URLs and remove the ones that doesn't belong
// to the given hostname
func FilterByHostname(hostname string, urls []*url.URL) []*url.URL {
result := []*url.URL{}
for _, u := range urls {
// TODO: handle relative paths
target := u.Hostname()
if len(target) < len(hostname) {
continue
}
match := true
for i, j := len(hostname)-1, len(target)-1; i >= 0 && j >= 0; i, j = i-1, j-1 {
if hostname[i] != target[j] {
match = false
break
}
}
if match {
result = append(result, u)
}
}
return result
}
// GetBody takes an URL as parameter, performs a GET and returns its body
func GetBody(rawurl string) (string, error) {
resp, err := http.Get(rawurl)
if err != nil {
return "", err
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(body), nil
}
// Crawl takes a base URL and builds a site map from it.
// delay is the time in miliseconds to wait between one request and another
func Crawl(baseURL string, level, delay int, verbose bool) (map[string][]*url.URL, error) {
bu, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
hostname := bu.Hostname()
type Item struct {
URL *url.URL
Level int
}
queue := []Item{Item{bu, 0}}
adjList := map[string][]*url.URL{}
for len(queue) > 0 {
u := queue[0]
queue = queue[1:]
currURL := u.URL.String()
if _, ok := adjList[currURL]; ok {
continue
}
body, err := GetBody(currURL)
if err != nil {
log.Printf("Error getting URL %v: %v\n", currURL, err)
continue
}
time.Sleep(time.Duration(delay) * time.Millisecond)
urls := ParseHTML(body)
if verbose {
var pad string
for i := 0; i <= u.Level; i++ {
pad = pad + "-"
}
pad += ">"
log.Println(pad + currURL)
}
adjList[currURL] = urls
filtered := FilterByHostname(hostname, urls)
if u.Level < level {
for _, f := range filtered {
queue = append(queue, Item{URL: f, Level: u.Level + 1})
}
}
}
return adjList, nil
}