-
Notifications
You must be signed in to change notification settings - Fork 0
/
links.go
81 lines (73 loc) · 1.74 KB
/
links.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
package links
import (
"bytes"
"fmt"
"golang.org/x/net/html"
"io/ioutil"
"net/http"
"net/url"
"os"
)
func writeFileIfOrigHost(b []byte, rawurl string, origHosts map[string]bool) error {
parsed, err := url.Parse(rawurl)
if err != nil {
return fmt.Errorf("url.Parse(%s) error [%v]", rawurl, err)
}
if origHosts[parsed.Host] {
return nil
}
path := "./got" + parsed.Path
if err := os.MkdirAll(path, 0777); err != nil {
return fmt.Errorf("os.MkdirAll(%s) error %v", path, err)
}
if err := ioutil.WriteFile(path+"/index.html", b, 0755); err != nil {
return fmt.Errorf("ioutil.WriteFile error %v", err)
}
return nil
}
func Extract(rawurl string, origHosts map[string]bool) ([]string, error) {
resp, err := http.Get(rawurl)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("getting %s: %s", rawurl, resp.Status)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("ioutil.ReadAll error %v", err)
}
doc, err := html.Parse(bytes.NewReader(b))
if err != nil {
return nil, fmt.Errorf("parsing %s as HTML: %v", rawurl, err)
}
var links []string
visitNode := func(n *html.Node) {
if n.Type == html.ElementNode && n.Data == "a" {
for _, a := range n.Attr {
if a.Key != "href" {
continue
}
link, err := resp.Request.URL.Parse(a.Val)
if err != nil {
continue
}
links = append(links, link.String())
}
}
}
forEachNode(doc, visitNode, nil)
return links, writeFileIfOrigHost(b, rawurl, origHosts)
}
func forEachNode(n *html.Node, pre, post func(n *html.Node)) {
if pre != nil {
pre(n)
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
forEachNode(c, pre, post)
}
if post != nil {
post(n)
}
}