Skip to content

Instantly share code, notes, and snippets.

@moccos
Created April 13, 2019 09:36
Show Gist options
  • Save moccos/46fc0ef9484469cdf5d387eb7e7424aa to your computer and use it in GitHub Desktop.
Save moccos/46fc0ef9484469cdf5d387eb7e7424aa to your computer and use it in GitHub Desktop.
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 Cacher struct {
v map[string]*fakeResult
m sync.Mutex
}
func (c *Cacher) get(url string) *fakeResult {
c.m.Lock()
defer c.m.Unlock()
return c.v[url]
}
func (c *Cacher) set(url string, result *fakeResult) {
c.m.Lock()
defer c.m.Unlock()
c.v[url] = result
fmt.Println(" set cache: " + url)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, ch chan int, cache *Cacher) {
if depth <= 0 {
ch <- 0
return
}
result := cache.get(url)
var body string
var urls []string
if result != nil {
fmt.Println(" got from cache :" + url)
body, urls = result.body, result.urls
} else {
var err error
body, urls, err = fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
ch <- -1
return
}
cache.set(url, &fakeResult{body, urls})
}
fmt.Printf("found: %s %q\n", url, body)
ch_children := make(chan int)
for _, u := range urls {
go Crawl(u, depth-1, fetcher, ch_children, cache)
}
for i := 0; i < len(urls); i++ {
<-ch_children
}
ch <- 0
}
func main() {
ch := make(chan int)
cache := Cacher{v: make(map[string]*fakeResult)}
go Crawl("https://golang.org/", 4, fetcher, ch, &cache)
<-ch
}
// 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