Skip to content

Instantly share code, notes, and snippets.

@AnatolyShirykalov
Created March 20, 2017 11:31
Show Gist options
  • Select an option

  • Save AnatolyShirykalov/bce69e47e9f52b8904f9aab344fadfd5 to your computer and use it in GitHub Desktop.

Select an option

Save AnatolyShirykalov/bce69e47e9f52b8904f9aab344fadfd5 to your computer and use it in GitHub Desktop.
Crawl from go tour
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)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, res *safeResults, q chan int) {
//fmt.Println("start Crawl depth", depth)
if depth <= 0 {
q <- 1
return
}
res.mux.Lock()
_, ok := res.v[url]
if ok != true {
// fmt.Println("Add", url)
res.v[url] = true
}
res.mux.Unlock()
if ok == true {
// fmt.Println("Skip", url)
q <- 1
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
// fmt.Println(err)
q <- 1
return
}
fmt.Printf("found: %s %q\n", url, body)
nq := make(chan int)
for _, u := range urls {
// fmt.Println("Next url", u, depth-1)
go Crawl(u, depth-1, fetcher, res, nq)
}
for _, v := range urls {
fmt.Println("done", v, <-nq)
}
q <- 1
return
}
func main() {
q := make(chan int, 100)
res := safeResults{v: make(map[string]bool)}
go Crawl("http://golang.org/", 4, fetcher, &res, q)
fmt.Println("Global done", <-q)
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
type safeResults struct {
v map[string]bool
mux sync.Mutex
}
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{
"http://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"http://golang.org/pkg/",
"http://golang.org/cmd/",
},
},
"http://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"http://golang.org/",
"http://golang.org/cmd/",
"http://golang.org/pkg/fmt/",
"http://golang.org/pkg/os/",
},
},
"http://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment