Skip to content

Instantly share code, notes, and snippets.

@kevinclcn
Last active March 18, 2018 01:06
Show Gist options
  • Select an option

  • Save kevinclcn/f519686fca0f93e30aac8074eb32f79a to your computer and use it in GitHub Desktop.

Select an option

Save kevinclcn/f519686fca0f93e30aac8074eb32f79a to your computer and use it in GitHub Desktop.
golang tutorial web crawler
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{
urlMap map[string]bool
mux sync.Mutex
}
func (c *Cache) Add(url string) {
c.mux.Lock()
c.urlMap[url] = true
c.mux.Unlock()
}
func (c *Cache) Has(url string) bool {
c.mux.Lock()
defer c.mux.Unlock()
return c.urlMap[url]
}
type result struct {
url string
depth int
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) {
var c = Cache{urlMap: make(map[string]bool)}
queue := make(chan result, 1)
fetch := func (url string, depth int, queue chan<- result) {
body, urls, err := fetcher.Fetch(url)
queue <- result{url, depth, body, urls, err}
}
go fetch(url, depth, queue)
c.Add(url)
for fetching := 1;fetching > 0;fetching-- {
res := <- queue
if res.err != nil {
fmt.Println(res.err)
continue
}
fmt.Printf("found: %s %q\n", res.url, res.body)
if res.depth <= 0 {
continue
}
for _, u := range res.urls {
if c.Has(u) {
continue
}
go fetch(u, res.depth-1, queue)
fetching++
c.Add(u)
}
}
close(queue)
return
}
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