Skip to content

Instantly share code, notes, and snippets.

@mtso
Last active December 16, 2016 07:19
Show Gist options
  • Save mtso/07bd2395baad2fa97ba26a8571aba8b7 to your computer and use it in GitHub Desktop.
Save mtso/07bd2395baad2fa97ba26a8571aba8b7 to your computer and use it in GitHub Desktop.
// My primitive solution to the web crawler exercise in the go tool tour
// Definitely need more practice on concurrency patterns and error package usage
//
// After much frustration, I ended up peeking at the official solution:
// https://github.com/golang/tour/blob/master/solutions/webcrawler.go
// so, I stole these ideas:
// the use of a concurrent closure
// iterating through the done channel
package main
import (
"fmt"
"sync"
)
var mux sync.Mutex
var visited = make(map[string]bool)
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) {
if depth <= 0 {
return
}
mux.Lock()
if visited[url] {
mux.Unlock()
fmt.Println("already visited: " + url)
return
}
visited[url] = true
mux.Unlock()
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("found "+body, url)
done := make(chan bool)
for _, url := range urls {
go func(url string) {
Crawl(url, depth-1, fetcher)
done <- true
}(url)
}
for _ = range urls {
<-done
}
return
}
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