Skip to content

Instantly share code, notes, and snippets.

@cedarmora
Created June 12, 2018 21:56
Show Gist options
  • Save cedarmora/0a206f46fc29b844820c4542a36144d1 to your computer and use it in GitHub Desktop.
Save cedarmora/0a206f46fc29b844820c4542a36144d1 to your computer and use it in GitHub Desktop.
A Tour of Go, Exercise: Web Crawler
// Inspired by https://gist.github.com/Trii/382723ae871fca080333697142dcdcc1
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 Cache struct {
cache map[string]bool
mux sync.Mutex
}
type Response struct {
url string
body string
}
func Crawl(url string, depth int, fetcher Fetcher, ch chan Response) {
defer close(ch)
cache := Cache{cache: make(map[string]bool)}
var waitGroup sync.WaitGroup
waitGroup.Add(1)
go CrawlRecursive(url, depth, fetcher, cache, ch, &waitGroup)
waitGroup.Wait()
}
// CrawlRecursive uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func CrawlRecursive(url string, depth int, fetcher Fetcher, cache Cache, ch chan Response, waitGroup *sync.WaitGroup) {
defer waitGroup.Done()
if depth <= 0 {
return
}
cache.mux.Lock()
if cache.cache[url] {
cache.mux.Unlock()
return
} else {
cache.cache[url] = true
cache.mux.Unlock()
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
ch <- Response{url, body}
for _, u := range urls {
waitGroup.Add(1)
go CrawlRecursive(u, depth-1, fetcher, cache, ch, waitGroup)
}
return
}
func main() {
ch := make(chan Response)
go Crawl("https://golang.org/", 4, fetcher, ch)
for response := range ch {
fmt.Printf("found: %s %q\n", response.url, response.body)
}
}
// 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