Skip to content

Instantly share code, notes, and snippets.

@nabeken
Created November 4, 2013 07:54
Show Gist options
  • Save nabeken/7299435 to your computer and use it in GitHub Desktop.
Save nabeken/7299435 to your computer and use it in GitHub Desktop.
A tour of Go #71
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) {
// TODO: Fetch URLs in parallel. (finished)
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
if _, ok := fetched_url[url]; ok {
fmt.Println(url, "has been crawled")
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
// marked crawled
fetched_url[url] = true
fmt.Printf("found: %s %q\n", url, body)
fmt.Println(urls, "urls found", "in", url)
q := make(chan string)
for _, u := range urls {
fmt.Println("Launching crawler with", u)
go func(url string) {
Crawl(url, depth-1, fetcher)
q <- url
}(u)
fmt.Println("Launched crawler with", u)
}
for quit := 0; quit < len(urls); quit++ {
fmt.Println("Waiting for crawler to complete.. remaining ", len(urls) - quit - 1)
<-q
fmt.Println("finishd! remaining", len(urls) - quit - 1)
}
}
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/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
var fetched_url = map[string]bool{}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment