Skip to content

Instantly share code, notes, and snippets.

@heathhenley
Created March 29, 2020 19:15
Show Gist options
  • Save heathhenley/7e7ed93d6b847e00a6d1bda2c978d58f to your computer and use it in GitHub Desktop.
Save heathhenley/7e7ed93d6b847e00a6d1bda2c978d58f to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"sync"
"time"
)
// SafeUrl is safe to use concurrently.
type SafeUrl struct {
v map[string]bool
mux 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)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher,
urls_map *SafeUrl) {
if depth <= 0 {
return
}
urls_map.mux.Lock()
if _, ok := urls_map.v[url]; ok {
urls_map.mux.Unlock()
return
} else {
urls_map.v[url] = true
urls_map.mux.Unlock()
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
go Crawl(u, depth-1, fetcher, urls_map)
}
return
}
func main() {
urls_map := SafeUrl{v: make(map[string]bool)}
go Crawl("https://golang.org/", 4, fetcher, &urls_map)
// This is to make sure the goroutines complete, it would be better
// to use a wait group.
time.Sleep(time.Second)
for k, v := range urls_map.v {
fmt.Println(k, v)
}
}
// 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