Skip to content

Instantly share code, notes, and snippets.

@ibeauregard
Last active June 23, 2022 19:51
Show Gist options
  • Save ibeauregard/58e46eecf534cec754c79d0bbd0e28af to your computer and use it in GitHub Desktop.
Save ibeauregard/58e46eecf534cec754c79d0bbd0e28af to your computer and use it in GitHub Desktop.
A solution for the Web Crawler concurrency exercise in the Tour of Go (https://go.dev/tour/concurrency/10)
package main
import (
"fmt"
"sync"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that page.
Fetch(url string) (body string, urls []string, err error)
}
type History struct {
mu sync.Mutex
set map[string]struct{}
}
func (hist *History) HasSeen(url string) bool {
hist.mu.Lock()
_, seen := hist.set[url]
hist.set[url] = struct{}{}
hist.mu.Unlock()
return seen
}
var hist History = History{set: make(map[string]struct{})}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, ret chan string) {
defer close(ret)
if depth <= 0 || hist.HasSeen(url) {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
ret <-err.Error()
return
}
ret <-fmt.Sprintf("found: %s %q", url, body)
result := make([]chan string, len(urls))
for i, u := range urls {
result[i] = make(chan string)
go Crawl(u, depth-1, fetcher, result[i])
}
for i := range result {
for s := range result[i] {
ret <-s
}
}
}
func main() {
result := make(chan string)
go Crawl("https://golang.org/", 4, fetcher, result)
for s := range result {
fmt.Println(s)
}
}
// fakeFetcher is Fetcher that returns canned results.
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)
}
// fetcher is a populated fakeFetcher.
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/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment