Skip to content

Instantly share code, notes, and snippets.

@pandaman64
Created October 18, 2017 01:47
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 pandaman64/20c7f47551afaa2ff69dd5352eeecf3b to your computer and use it in GitHub Desktop.
Save pandaman64/20c7f47551afaa2ff69dd5352eeecf3b to your computer and use it in GitHub Desktop.
Exercise: Web Crawler
package main
import (
"fmt"
"sync"
)
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 SharedState struct {
messages chan string
visited map[string]interface{}
mux sync.Mutex
wg sync.WaitGroup
}
func CrawlImpl(state *SharedState, url string, depth int, fetcher Fetcher) {
defer state.wg.Done()
if depth <= 0 {
return
}
state.mux.Lock()
if _, ok := state.visited[url]; !ok {
state.visited[url] = nil
body, urls, err := fetcher.Fetch(url)
if err != nil {
state.mux.Unlock()
return
}
state.messages <- fmt.Sprintf("%s found: %s", url, body)
state.mux.Unlock()
for _, url = range urls {
if _, ok = state.visited[url]; !ok {
state.wg.Add(1)
go CrawlImpl(state, url, depth - 1, fetcher)
}
}
} else {
state.mux.Unlock()
}
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
state := SharedState {
messages: make(chan string),
visited: make(map[string]interface{}),
}
state.wg.Add(1)
go func() {
state.wg.Wait()
close(state.messages)
}()
go CrawlImpl(&state, url, depth, fetcher)
for m := range state.messages {
fmt.Println(m)
}
}
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/",
},
},
"http://golang.org/cmd/": &fakeResult{
"Commands",
[]string{
"http://golang.org/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment