Skip to content

Instantly share code, notes, and snippets.

@caiolouro
Created March 13, 2022 23:24
Show Gist options
  • Save caiolouro/cc5272bf0f8d273ab879e3fb0b609f07 to your computer and use it in GitHub Desktop.
Save caiolouro/cc5272bf0f8d273ab879e3fb0b609f07 to your computer and use it in GitHub Desktop.
Tour Of Go Web Crawler Exercise Solution
// https://go.dev/tour/concurrency/10
package main
import (
"fmt"
"sync"
)
type UrlSeen struct {
mu sync.Mutex
seen map[string]bool
}
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)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, seen *UrlSeen) {
var wg sync.WaitGroup
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
seen.mu.Lock()
if seen.seen[url] == true {
//fmt.Println("url skipped", url)
seen.mu.Unlock()
return
}
fmt.Println("gonna read", url)
seen.seen[url] = true
seen.mu.Unlock()
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
//fmt.Printf("found: %s %q %d suburls\n", url, body, len(urls))
fmt.Printf("read content %q\n", body)
for _, u := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
Crawl(u, depth-1, fetcher, seen)
}(u)
}
wg.Wait()
return
}
func main() {
seen := UrlSeen{seen: make(map[string]bool)}
Crawl("https://golang.org/", 4, fetcher, &seen)
fmt.Println("seen", seen)
}
// 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