-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
103 lines (82 loc) · 1.72 KB
/
main.go
File metadata and controls
103 lines (82 loc) · 1.72 KB
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
package main
import (
"fmt"
"golang.org/x/net/html"
"net/http"
"os"
"strings"
)
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 retrieveUrls(url string, urlChannel chan string, channelFinished chan bool) {
response, err := http.Get(url)
z := html.NewTokenizer(response.Body)
defer func() {
channelFinished <- true
}()
defer response.Body.Close()
if err != nil {
fmt.Println("Failed to gather links!")
return
}
for {
tt := z.Next()
switch {
case tt == html.ErrorToken:
return
case tt == html.StartTagToken:
t := z.Token()
isAnchor := t.Data == "a"
if !isAnchor {
continue
}
isHref, hrefValue := getHref(t)
if !isHref {
continue
}
isHttpLink := strings.Index(hrefValue, "http") == 0
if isHttpLink {
urlChannel <- hrefValue
}
}
}
}
func fireURlWorkers(urls []string) []string {
var foundUrls []string
urlChannel := make(chan string)
channelFinished := make(chan bool)
for _, url := range urls {
go retrieveUrls(url, urlChannel, channelFinished)
}
for i := 0; i < len(urls); {
select {
case url := <-urlChannel:
foundUrls = append(foundUrls, url)
case <-channelFinished:
i++
}
}
defer close(urlChannel)
return foundUrls
}
func printUrls(urls []string) {
for _, url := range urls {
fmt.Println(" - " + url)
}
}
func main() {
urls := fireURlWorkers(os.Args[1:])
originalUrlsCount := len(urls)
printUrls(urls)
urls = fireURlWorkers(urls)
printUrls(urls)
fmt.Println("\nFound", originalUrlsCount, "unique urls from original url(s) provided\n")
fmt.Println("\nFound", len(urls), "additional unique urls found on linked pages\n")
}