Skip to content

Instantly share code, notes, and snippets.

@sbuckle
Created July 21, 2021 17:50
Show Gist options
  • Select an option

  • Save sbuckle/577852a3b7b197029cabb1bdf2b3281b to your computer and use it in GitHub Desktop.

Select an option

Save sbuckle/577852a3b7b197029cabb1bdf2b3281b 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 Cache struct {
mu sync.RWMutex
v map[string]bool
}
func (c *Cache) Set(url string) {
c.mu.Lock()
c.v[url] = true
c.mu.Unlock()
}
func (c *Cache) Get(url string) bool {
c.mu.RLock()
defer c.mu.RUnlock()
return c.v[url]
}
var cache = newCache()
// 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
}
if cache.Get(url) {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
cache.Set(url)
var wg sync.WaitGroup
for _, u := range urls {
wg.Add(1)
go func(url string) {
Crawl(url, depth-1, fetcher)
wg.Done()
}(u)
}
wg.Wait()
return
}
func newCache() Cache {
return Cache{
v: make(map[string]bool),
}
}
func main() {
Crawl("https://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{
"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