Skip to content

Instantly share code, notes, and snippets.

@mjmac
Last active August 29, 2015 14:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjmac/a2f51e9963a07d0edc28 to your computer and use it in GitHub Desktop.
Save mjmac/a2f51e9963a07d0edc28 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 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) {
resultChan := make(chan *result)
mapChan := make(chan map[string]bool)
doneChan := make(chan bool)
allDone := false
seen := make(map[string]bool)
var _crawl func(string, int, Fetcher, chan bool)
_crawl = func(url string, depth int, fetcher Fetcher, doneChannel chan bool) {
var seen map[string]bool
var body string
var urls []string
var err error
childFinished := make(chan bool)
children := 0
if depth <= 0 {
goto done
}
seen = <- mapChan
if seen[url] {
mapChan <- seen
goto done
} else {
seen[url] = true
mapChan <- seen
}
body, urls, err = fetcher.Fetch(url)
if err != nil {
resultChan <- &result{err, body, url}
goto done
}
resultChan <- &result{nil, body, url}
for _, u := range urls {
go _crawl(u, depth-1, fetcher, childFinished)
children++
}
for ; children > 0; children-- {
<- childFinished
}
done:
doneChannel <- true
}
go _crawl(url, depth, fetcher, doneChan)
for ; !allDone; {
select {
case mapChan <- seen:
seen = <- mapChan
case result := <- resultChan:
if result.err != nil {
fmt.Println(result.err)
} else {
fmt.Printf("found: %s %q\n", result.url, result.body)
}
case allDone = <- doneChan:
break
}
}
}
func main() {
Crawl("http://golang.org/", 4, fetcher)
}
type result struct {
err error
body string
url string
}
// 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