Skip to content

Instantly share code, notes, and snippets.

@styx
Last active March 12, 2018 08:18
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 styx/20e941da10e990922ff04a3d483d36d6 to your computer and use it in GitHub Desktop.
Save styx/20e941da10e990922ff04a3d483d36d6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
)
type Cache struct {
data map[string]string
m sync.Mutex
}
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)
}
func (c *Cache) Add(url, body string) {
c.m.Lock()
c.data[url] = body
c.m.Unlock()
}
func (c *Cache) Present(url string) bool {
c.m.Lock()
defer c.m.Unlock()
_, ok := c.data[url]
return ok
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, cache *Cache) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
var wg sync.WaitGroup
if depth <= 0 {
return
}
if cache.Present(url) {
fmt.Printf("Already fetched: %s\n", url)
} else {
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
cache.Add(url, body)
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
wg.Add(1)
go func(u string) {
defer wg.Done()
Crawl(u, depth-1, fetcher, cache)
}(u)
}
}
wg.Wait()
}
func main() {
cache := &Cache{data: make(map[string]string)}
Crawl("https://golang.org/", 4, fetcher, cache)
}
// 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