Skip to content

Instantly share code, notes, and snippets.

@alexvictoor
Last active August 29, 2015 14:05
Show Gist options
  • Save alexvictoor/297b3fd3cb5016effe99 to your computer and use it in GitHub Desktop.
Save alexvictoor/297b3fd3cb5016effe99 to your computer and use it in GitHub Desktop.
My solution to the golang webcrawler exercise
package main
import (
"fmt"
)
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 Task struct {
url string
depth int
}
type TaskResult struct {
url string
depth int
error error
body string
urls []string
}
func Crawl(url string, depth int, fetcher Fetcher) {
results := make(chan TaskResult)
ongoingTasks := 0
fetchedUrls := make(map[string]bool)
crawl := func(t Task) {
if t.depth > 0 && !fetchedUrls[t.url] {
ongoingTasks++
fetchedUrls[t.url] = true
go func() {
body, urls, err := fetcher.Fetch(t.url)
results <- TaskResult{t.url, t.depth, err, body, urls}
}()
}
}
crawl(Task{url, depth})
for {
select {
case r := <-results:
ongoingTasks--
if r.error != nil {
fmt.Println(r.error)
} else {
fmt.Printf("found: %s %q\n", r.url, r.body)
for _, u := range r.urls {
crawl(Task{u, r.depth - 1})
}
}
default:
if ongoingTasks == 0 {
return
}
}
}
}
func main() {
Crawl("http://golang.org/", 4, fetcher)
}
// 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/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment