Skip to content

Instantly share code, notes, and snippets.

@rkotov93
Created March 22, 2016 00:42
Show Gist options
  • Save rkotov93/16b0a676fa737e284698 to your computer and use it in GitHub Desktop.
Save rkotov93/16b0a676fa737e284698 to your computer and use it in GitHub Desktop.
Exercise: Web Crawler
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, messenger chan string) {
defer close(messenger)
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 || visits[url] == true {
return
}
visits[url] = true
body, urls, err := fetcher.Fetch(url)
if err != nil {
messenger <- err.Error()
return
}
messenger <- fmt.Sprintf("found: %s %q\n", url, body)
for _, u := range urls {
recmessenger := make(chan string)
go Crawl(u, depth-1, fetcher, recmessenger)
for message := range recmessenger {
messenger <- message
}
}
return
}
func doCrawl(url string, depth int, fetcher Fetcher) {
visits = make(map[string]bool)
messenger := make(chan string)
go Crawl(url, depth, fetcher, messenger)
for message := range messenger {
fmt.Print(message)
}
}
func main() {
doCrawl("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\n", url)
}
var visits map[string]bool
// 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