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 116 117 118 119 120
| package main
import ( "fmt" "sync" "time" )
type Fetcher interface { Fetch(url string) (body string, urls []string, err error) }
type SafeCrawl struct { myMap map[string]string mux sync.Mutex }
func (safeCrawl *SafeCrawl) addOne(url, body string, err error) {
if err != nil { if _, ok := safeCrawl.myMap[url]; !ok { safeCrawl.mux.Lock() safeCrawl.myMap[url] = "" fmt.Println(err) safeCrawl.mux.Unlock() } return }
if _, ok := safeCrawl.myMap[url]; !ok { safeCrawl.mux.Lock() safeCrawl.myMap[url] = body fmt.Printf("found: %s %q\n", url, safeCrawl.myMap[url]) safeCrawl.mux.Unlock() }
}
func Crawl(url string, depth int, fetcher Fetcher, safeCrawl SafeCrawl) { if depth <= 0 { return }
body, urls, err := fetcher.Fetch(url)
safeCrawl.addOne(url, body, err)
for _, u := range urls { Crawl(u, depth-1, fetcher, safeCrawl) } return }
func main() { safeCrawl := SafeCrawl{ myMap: make(map[string]string), } go Crawl("https://golang.org/", 4, fetcher, safeCrawl) go Crawl("https://golang.org/", 4, fetcher, safeCrawl) go Crawl("https://golang.org/", 4, fetcher, safeCrawl) go Crawl("https://golang.org/", 4, fetcher, safeCrawl) go Crawl("https://golang.org/", 4, fetcher, safeCrawl) time.Sleep(time.Second)
}
type fakeFetcher map[string]*fakeResult
type fakeResult struct { body string urls []string }
func (f fakeFetcher) Fetch(url string) (string, []string, error) { if res, ok := f[url]; ok { return res.body, res.urls, nil } return "", nil, fmt.Errorf("not found: %s", url) }
var fetcher = fakeFetcher{ "https://golang.org/": &fakeResult{ "The Go Programming Language", []string{ "https://golang.org/pkg/", "https://golang.org/cmd/", }, }, "https://golang.org/pkg/": &fakeResult{ "Packages", []string{ "https://golang.org/", "https://golang.org/cmd/", "https://golang.org/pkg/fmt/", "https://golang.org/pkg/os/", }, }, "https://golang.org/pkg/fmt/": &fakeResult{ "Package fmt", []string{ "https://golang.org/", "https://golang.org/pkg/", }, }, "https://golang.org/pkg/os/": &fakeResult{ "Package os", []string{ "https://golang.org/", "https://golang.org/pkg/", }, }, }
|