Skip to content

Instantly share code, notes, and snippets.

@danx12
Created March 10, 2019 07:48
Show Gist options
  • Save danx12/ac7aa844d5cde579d45faee68829a917 to your computer and use it in GitHub Desktop.
Save danx12/ac7aa844d5cde579d45faee68829a917 to your computer and use it in GitHub Desktop.
Exercise: Web Crawler - A Tour of Go
package main
import (
"fmt"
"sync"
)
type Cache struct {
v map[string]int
mux sync.Mutex
}
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, cache *Cache, quit chan bool) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
quit <- true
return
}
cache.mux.Lock()
if _, ok := cache.v[url]; ok {
cache.mux.Unlock()
quit <- true
return
}
cache.v[url]++
cache.mux.Unlock()
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
quit <- true
return
}
fmt.Printf("found: %s %q\n", url, body)
chs := make([]chan bool,len(urls))
//fmt.Println(len(chs))
for i, u := range urls {
chs[i] = make(chan bool)
go Crawl(u, depth-1, fetcher, cache,chs[i])
}
for _, ch := range chs {
<- ch
}
quit <-true
return
}
func main() {
cache := Cache{v:make(map[string]int)}
quit:= make(chan bool)
go Crawl("https://golang.org/", 4, fetcher, &cache, quit)
<- quit
}
// 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