/
webclient.go
144 lines (113 loc) · 3.15 KB
/
webclient.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
package wcrawler
import (
"io"
"net/http"
"net/http/httptrace"
"time"
"golang.org/x/net/html"
)
// WebClient is responsible to connect to the links and manage connections to websites.
// Implements Connector interface.
type WebClient struct {
client *http.Client
}
// NewWebClient returns a new WebClient.
func NewWebClient(client *http.Client) *WebClient {
return &WebClient{client: client}
}
// GetLinks returns all the links found in the webpage.
func (c *WebClient) GetLinks(rawURL string) (statusCode int, links []URLEntity, latency time.Duration, err error) {
// make sure to use the same http.Client to reuse connections to get links
// from other pages being served by the same server.
// Check for robot.txt, maybe?
req, err := http.NewRequest("GET", rawURL, nil)
if err != nil {
return 0, links, latency, err
}
var start time.Time
trace := &httptrace.ClientTrace{
GotFirstResponseByte: func() {
latency = time.Since(start)
},
}
req = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))
start = time.Now()
resp, err := c.client.Do(req)
if err != nil {
return 0, links, latency, err
}
defer resp.Body.Close()
statusCode = resp.StatusCode
if statusCode < 200 || statusCode >= 300 {
return statusCode, links, latency, nil
}
links, err = c.parse(rawURL, resp.Body)
return statusCode, links, latency, err
}
// parse parses the webpage looking for links.
func (c *WebClient) parse(rawURL string, r io.Reader) (links []URLEntity, err error) {
// Parse <base> tag inside <head> tag if it exists
// Parse all <a> tags
// Cater for the fact that a <a> link might be a mailto or a phone or something else.
// Check if "Opaque" field in URL struct is set
// Validate whether they are absolute or relative tags. Also check if the relative tags start with a /
// TODO: Make sure body is utf-8 encoded
insideHead := false
baseURL := rawURL
links = []URLEntity{}
z := html.NewTokenizer(r)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
// EOF
return links, nil
case tt == html.StartTagToken || tt == html.SelfClosingTagToken:
t := z.Token()
if t.Data == "head" {
insideHead = true
}
// This only works assuming href in <base> is absolute.
// TODO: confirm this in the HTML spec.
if t.Data == "base" && insideHead == true {
ok, rawURL := getHref(t)
if ok {
baseURL = rawURL
}
}
// Check if the token is an <a> tag
isAnchor := t.Data == "a"
if !isAnchor {
continue
}
// Extract the href value, if there is one
ok, rawURL := getHref(t)
if !ok {
continue
}
// rawURL = strings.TrimSpace(rawURL)
// Deals with absolute and relative URLs.
urlEntity, err := JoinURLs(baseURL, rawURL)
if err != nil {
continue
}
links = append(links, urlEntity)
case tt == html.EndTagToken:
t := z.Token()
if t.Data == "head" {
insideHead = false
}
}
}
}
// getHref returns the href attribute from a Token.
func getHref(t html.Token) (ok bool, href string) {
// Iterate over all of the Token's attributes until it finds an "href"
for _, a := range t.Attr {
if a.Key == "href" {
href = a.Val
ok = true
}
}
return
}