Skip to content

Instantly share code, notes, and snippets.

@scheakur
Created November 3, 2013 05:28
Show Gist options
  • Save scheakur/7287098 to your computer and use it in GitHub Desktop.
Save scheakur/7287098 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type Fetcher interface {
// Fetch returns the body of URL and
// a slice of URLs found on that result.
Fetch(url string) (body string, urls []string, err error)
}
// Crawl uses fetcher to recursively crawl
// results starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
result := make(chan Result)
quit := make(chan int)
fetchedUrls := make(map[string]bool)
nowFetching := 0
crawl := func (url string, depth int) {
nowFetching += 1
fetchedUrls[url] = true
go fetch(url, depth, fetcher, result, quit)
}
crawl(url, depth)
for {
select {
case res := <-result:
if res.err != nil {
fmt.Println(res.err)
break
}
fmt.Printf("found: %s %q\n", res.url, res.body)
for _, u := range res.urls {
if !fetchedUrls[u] {
crawl(u, res.depth - 1)
}
}
case <-quit:
if nowFetching -= 1; nowFetching == 0 {
return
}
}
}
return
}
func fetch(url string, depth int, fetcher Fetcher,
result chan Result, quit chan int) {
if depth <= 0 {
quit <- 0
return
}
body, urls, err := fetcher.Fetch(url)
result <- Result{url, body, depth, urls, err}
quit <- 0
}
type Result struct {
url string
body string
depth int
urls []string
err error
}
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