-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
90 lines (73 loc) · 1.29 KB
/
main.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
package main
import (
"fmt"
"net/http"
"os"
"strings"
"golang.org/x/net/html"
)
func getHref(t html.Token) (ok bool, href string) {
for _, a := range t.Attr {
if a.Key == "href" {
href = a.Val
ok = true
}
}
return
}
func crawl(url string, ch chan string, chFinished chan bool) {
resp, err := http.Get(url)
defer func() {
chFinished <- true
}()
if err != nil {
fmt.Println("Err:failed to crawl:", url)
return
}
b := resp.Body
defer b.Close()
z := html.NewTokenizer(b)
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
return
case tt == html.StartTagToken:
t := z.Token()
isAnchor := t.Data == "a"
if !isAnchor {
continue
}
ok, url := getHref(t)
if !ok {
continue
}
hasProto := strings.Index(url, "http") == 0
if hasProto {
ch <- url
}
}
}
}
func main() {
foundUrls := make(map[string]bool)
seedUrls := os.Args[1:]
chUrls := make(chan string)
chFinished := make(chan bool)
for _, url := range seedUrls {
go crawl(url, chUrls, chFinished)
}
for c := 0; c < len(seedUrls); {
select {
case url := <-chUrls:
foundUrls[url] = true
case <-chFinished:
c++
}
}
fmt.Println("\nFound", len(foundUrls), "unique urls:\n")
for url, _ := range foundUrls {
fmt.Println("-" + url)
}
close(chUrls)
}