summaryrefslogtreecommitdiff
path: root/main.go
blob: 3f29a267985548d0d4bbb31e23e777ea08104b9b (plain)
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
104
105
106
107
108
109
110
111
112
113
114
115
// URLs implements a breadth-first search webcrawler based on the
// example given in section 8.6 of The Go Programming Language.
package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"net/url"
)

func main() {
	maxConcurrency := flag.Int("c", 0, "Maximum number of concurrent queue pushes")
	startRawURL := flag.String("url", "", "Entry-point URL")
	maxURLs := flag.Int("max", 0, "Maximum number of URLs to collect (omitted or 0 means no limit)")

	flag.Parse()

	if *maxConcurrency == 0 {
		log.Fatal("Missing -c argument")
	}

	if *maxConcurrency < 1 {
		log.Fatalf("Invalid -c argument: %d", *maxConcurrency)
	}

	if *startRawURL == "" {
		log.Fatal("Missing -url argument")
	}

	if *maxURLs < 0 {
		log.Fatalf("Invalid -max argument: %d", *maxURLs)
	}

	startURL, err := url.Parse(*startRawURL)
	if err != nil {
		log.Fatal(err)
	}

	crawler(*startURL, *maxConcurrency, *maxURLs)

}

func crawler(startURL url.URL, maxConcurrency, maxURLs int) {
	/* Main logic starts here. */

	worklist := make(chan []url.URL)
	go func() {
		worklist <- []url.URL{startURL}
	}()

	sem := make(chan struct{}, maxConcurrency)
	ctx, cancel := context.WithCancel(context.Background())

	seen := make(map[url.URL]bool)
	i := 1

	// FIXME: unfortunately, this example leaks, but I don't know
	// how to fix that yet.
loop:
	for list := range worklist {
		for _, u := range list {
			if maxURLs > 0 && len(seen) == maxURLs {
				break loop
			}

			if !seen[u] {
				fmt.Printf("%d. %s\n", i, &u)
				i++
				seen[u] = true

				go func() {
					sem <- struct{}{}
					defer func() { <-sem }()

					more := getMoreURLs(ctx, u)
					if len(more) > 0 {
						worklist <- more
					}
				}()
			}
		}
	}

	// We broke the range loop, meaning there should be no more
	// pending getMoreURLs jobs anyway.
	cancel()

	// For now, print out some diagnostics that prove that there
	// are still pending sends on the worklist channel.
	for batch := range worklist {
		fmt.Printf("%d\n", len(batch))

		for _, u := range batch {
			fmt.Printf("-- %s\n", &u)
		}
	}
}

func getMoreURLs(ctx context.Context, u url.URL) []url.URL {
	select {
	case <-ctx.Done():
		return nil
	default:
	}

	doc, err := fetch(u)
	if err != nil {
		log.Print(err)
		return nil
	}

	return findURLs(u, doc)
}