Skip to content

Instantly share code, notes, and snippets.

@tai2
Created May 2, 2019 10:48
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 tai2/b67cfa0b61ab6b468981c277a6c87078 to your computer and use it in GitHub Desktop.
Save tai2/b67cfa0b61ab6b468981c277a6c87078 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)
}
var mux sync.Mutex
type UrlLocks map[string]*sync.Mutex
func (locks UrlLocks) Lock(url string) (first bool){
mux.Lock()
defer mux.Unlock()
lock, ok := locks[url]
if ok {
first = false
} else {
first = true
lock = &sync.Mutex{}
locks[url] = lock
}
lock.Lock()
return
}
func (locks UrlLocks) Unlock(url string) {
mux.Lock()
defer mux.Unlock()
lock := locks[url]
lock.Unlock()
}
var urlLocks UrlLocks = UrlLocks{}
func terminate(quit chan int) {
quit <- 0
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, quit chan int) {
defer terminate(quit)
if depth <= 0 {
return
}
first := urlLocks.Lock(url)
if !first {
urlLocks.Unlock(url)
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
urlLocks.Unlock(url)
return
}
fmt.Printf("found: %s %q %v\n", url, body, urls)
urlLocks.Unlock(url)
quits := make([](chan int), len(urls))
for i, u := range urls {
quits[i] = make(chan int)
go Crawl(u, depth-1, fetcher, quits[i])
}
for i := 0; i < len(urls); i++ {
<- quits[i]
}
}
func main() {
quit := make(chan int)
go Crawl("https://golang.org/", 4, fetcher, quit)
<- quit
}
// 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