Created
February 22, 2015 20:22
-
-
Save davidcrawford/b5774e20479a48dea298 to your computer and use it in GitHub Desktop.
Golang Tour of Go: Web Crawler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 FetchResult struct { | |
Url string | |
Body string | |
Urls []string | |
Depth int | |
Error error | |
} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher) { | |
fetched := make(map[string]bool) | |
fetchAsync := func(url string, depth int, ch chan *FetchResult) { | |
body, urls, err := fetcher.Fetch(url) | |
ch <- &FetchResult{url, body, urls, depth, err} | |
} | |
resultChan := make(chan *FetchResult) | |
fetched[url] = true | |
go fetchAsync(url, 1, resultChan) | |
waitingFor := 1 | |
for waitingFor > 0 { | |
result := <-resultChan | |
waitingFor-- | |
if result.Error != nil { | |
fmt.Println(result.Error) | |
continue | |
} | |
fmt.Printf("Found %s %q\n", result.Url, result.Body) | |
if result.Depth < depth { | |
for _, url := range result.Urls { | |
if !fetched[url] { | |
fetched[url] = true | |
go fetchAsync(url, result.Depth + 1, resultChan) | |
waitingFor++ | |
} | |
} | |
} | |
} | |
} | |
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