-
Notifications
You must be signed in to change notification settings - Fork 13
/
crawl.go
97 lines (84 loc) · 1.71 KB
/
crawl.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
package main
import (
"crypto/tls"
"flag"
"fmt"
"github.com/jackdanger/collectlinks"
"net/http"
"net/url"
"os"
)
func usage() {
fmt.Fprintf(os.Stderr, "usage: crawl http://example.com/path/file.html\n")
flag.PrintDefaults()
os.Exit(2)
}
func main() {
flag.Usage = usage
flag.Parse()
args := flag.Args()
fmt.Println(args)
if len(args) < 1 {
usage()
fmt.Println("Please specify start page")
os.Exit(1)
}
queue := make(chan string)
filteredQueue := make(chan string)
go func() { queue <- args[0] }()
go filterQueue(queue, filteredQueue)
// introduce a bool channel to synchronize execution of concurrently running crawlers
done := make(chan bool)
// pull from the filtered queue, add to the unfiltered queue
for i := 0; i < 5; i++ {
go func() {
for uri := range filteredQueue {
enqueue(uri, queue)
}
done <- true
}()
}
<-done
}
func filterQueue(in chan string, out chan string) {
var seen = make(map[string]bool)
for val := range in {
if !seen[val] {
seen[val] = true
out <- val
}
}
}
func enqueue(uri string, queue chan string) {
fmt.Println("fetching", uri)
transport := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
client := http.Client{Transport: transport}
resp, err := client.Get(uri)
if err != nil {
return
}
defer resp.Body.Close()
links := collectlinks.All(resp.Body)
for _, link := range links {
absolute := fixUrl(link, uri)
if uri != "" {
go func() { queue <- absolute }()
}
}
}
func fixUrl(href, base string) string {
uri, err := url.Parse(href)
if err != nil {
return ""
}
baseUrl, err := url.Parse(base)
if err != nil {
return ""
}
uri = baseUrl.ResolveReference(uri)
return uri.String()
}