|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net/http" |
| 6 | + "runtime" |
| 7 | + "time" |
| 8 | + |
| 9 | + "golang.org/x/net/html" |
| 10 | +) |
| 11 | + |
| 12 | +var fetched map[string]bool |
| 13 | + |
| 14 | +type result struct { |
| 15 | + url string |
| 16 | + urls []string |
| 17 | + err error |
| 18 | + depth int |
| 19 | +} |
| 20 | + |
| 21 | +// Crawl uses findLinks to recursively crawl |
| 22 | +// pages starting with url, to a maximum of depth. |
| 23 | +func Crawl(url string, depth int) { |
| 24 | + runtime.GOMAXPROCS(runtime.NumCPU()) |
| 25 | + results := make(chan *result) |
| 26 | + |
| 27 | + fetch := func(url string, depth int) { |
| 28 | + urls, err := findLinks(url) |
| 29 | + results <- &result{url, urls, err, depth} |
| 30 | + } |
| 31 | + |
| 32 | + go fetch(url, depth) |
| 33 | + fetched[url] = true |
| 34 | + |
| 35 | + for fetching := 1; fetching > 0; fetching-- { |
| 36 | + res := <-results |
| 37 | + if res.err != nil { |
| 38 | + // fmt.Println(res.err) |
| 39 | + continue |
| 40 | + } |
| 41 | + |
| 42 | + fmt.Printf("found: %s\n", res.url) |
| 43 | + if res.depth > 0 { |
| 44 | + for _, u := range res.urls { |
| 45 | + if !fetched[u] { |
| 46 | + fetching++ |
| 47 | + go fetch(u, res.depth-1) |
| 48 | + fetched[u] = true |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + } |
| 53 | + close(results) |
| 54 | +} |
| 55 | + |
| 56 | +func main() { |
| 57 | + fetched = make(map[string]bool) |
| 58 | + now := time.Now() |
| 59 | + Crawl("http://github.com/aditya43", 2) |
| 60 | + fmt.Println("time taken:", time.Since(now)) |
| 61 | +} |
| 62 | + |
| 63 | +func findLinks(url string) ([]string, error) { |
| 64 | + resp, err := http.Get(url) |
| 65 | + if err != nil { |
| 66 | + return nil, err |
| 67 | + } |
| 68 | + if resp.StatusCode != http.StatusOK { |
| 69 | + resp.Body.Close() |
| 70 | + return nil, fmt.Errorf("getting %s: %s", url, resp.Status) |
| 71 | + } |
| 72 | + doc, err := html.Parse(resp.Body) |
| 73 | + resp.Body.Close() |
| 74 | + if err != nil { |
| 75 | + return nil, fmt.Errorf("parsing %s as HTML: %v", url, err) |
| 76 | + } |
| 77 | + return visit(nil, doc), nil |
| 78 | +} |
| 79 | + |
| 80 | +// visit appends to links each link found in n, and returns the result. |
| 81 | +func visit(links []string, n *html.Node) []string { |
| 82 | + if n.Type == html.ElementNode && n.Data == "a" { |
| 83 | + for _, a := range n.Attr { |
| 84 | + if a.Key == "href" { |
| 85 | + links = append(links, a.Val) |
| 86 | + } |
| 87 | + } |
| 88 | + } |
| 89 | + for c := n.FirstChild; c != nil; c = c.NextSibling { |
| 90 | + links = visit(links, c) |
| 91 | + } |
| 92 | + return links |
| 93 | +} |
0 commit comments