Skip to content

Instantly share code, notes, and snippets.

@pdkovacs
Last active September 8, 2018 18:46
Show Gist options
  • Save pdkovacs/5af03d9f9c8ef4fec73475863d7f007c to your computer and use it in GitHub Desktop.
Save pdkovacs/5af03d9f9c8ef4fec73475863d7f007c to your computer and use it in GitHub Desktop.
A Tour of Go: exercise-web-crawler.go
package main
import (
"fmt"
"sync"
"time"
)
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 {
body string
urls []string
err error
}
type cachingFetcher struct {
urlMap map[string]fetchResult
mux *sync.Mutex
fetcher Fetcher
}
func (cachingFetcher cachingFetcher) fetch(url string) fetchResult {
cachingFetcher.mux.Lock()
defer cachingFetcher.mux.Unlock()
if value, ok := cachingFetcher.urlMap[url]; ok {
fmt.Printf("found in cache: %s\n", url)
return value
}
body, urls, err := cachingFetcher.fetcher.Fetch(url)
value := fetchResult{body, urls, err}
cachingFetcher.urlMap[url] = value
return value
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher cachingFetcher) {
if depth <= 0 {
return
}
fetchResult := fetcher.fetch(url)
// fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", fetchResult)
if fetchResult.err != nil {
fmt.Println(fetchResult.err)
return
}
fmt.Printf("found: %s %q\n", url, fetchResult.body)
for _, u := range fetchResult.urls {
go Crawl(u, depth-1, fetcher)
}
return
}
func main() {
var myFetcher = cachingFetcher{make(map[string]fetchResult), &sync.Mutex{}, fetcher}
go Crawl("https://golang.org/", 4, myFetcher)
time.Sleep(1 * time.Second)
}
// 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{
"https://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"https://golang.org/pkg/",
"https://golang.org/cmd/",
},
},
"https://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"https://golang.org/",
"https://golang.org/cmd/",
"https://golang.org/pkg/fmt/",
"https://golang.org/pkg/os/",
},
},
"https://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
"https://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"https://golang.org/",
"https://golang.org/pkg/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment