I'm trying to solve Exercise: Web Crawler
In this exercise you'll use Go's concurrency features to parallelize a web crawler.
Modify the Crawl function to fetch URLs in parallel without fetching the same URL twice.
When should I check if all urls already been crawled? (or how could I know if there will be no more data queued?)
package main
import (
"fmt"
)
type Result struct {
Url string
Depth int
}
type Stor struct {
Queue chan Result
Visited map[string]int
}
func NewStor() *Stor {
return &Stor{
Queue: make(chan Result,1000),
Visited: map[string]int{},
}
}
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(res Result, fetcher Fetcher, stor *Stor) {
defer func() {
/*
if len(stor.Queue) == 0 {
close(stor.Queue)
}
*/ // this is wrong, it makes the channel closes too early
}()
if res.Depth <= 0 {
return
}
// TODO: Don't fetch the same URL twice.
url := res.Url
stor.Visited[url]++
if stor.Visited[url] > 1 {
fmt.Println("skip:",stor.Visited[url],url)
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q
", url, body)
for _, u := range urls {
stor.Queue <- Result{u,res.Depth-1}
}
return
}
func main() {
stor := NewStor()
Crawl(Result{"http://golang.org/", 4}, fetcher, stor)
for res := range stor.Queue {
// TODO: Fetch URLs in parallel.
go Crawl(res,fetcher,stor)
}
}
// 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{
"http://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"http://golang.org/pkg/",
"http://golang.org/cmd/",
},
},
"http://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"http://golang.org/",
"http://golang.org/cmd/",
"http://golang.org/pkg/fmt/",
"http://golang.org/pkg/os/",
},
},
"http://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
The output was a deadlock since the stor.Queue
channel never closed.