Skip to content

Instantly share code, notes, and snippets.

@ta1kt0me
Last active January 26, 2017 17:10
Show Gist options
  • Select an option

  • Save ta1kt0me/ada89b82dc9392667477dda8b0de2e17 to your computer and use it in GitHub Desktop.

Select an option

Save ta1kt0me/ada89b82dc9392667477dda8b0de2e17 to your computer and use it in GitHub Desktop.
Exercise: 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 UrlMapper struct {
v map[string]string
mux sync.Mutex
}
func (t *UrlMapper) Set(key string, value string) {
t.mux.Lock()
if _, ok := t.v[key]; !ok {
t.v[key] = value
}
t.mux.Unlock()
}
func (t *UrlMapper) Get(key string) string {
t.mux.Lock()
var v string
if _, ok := t.v[key]; ok {
v = t.v[key]
}
t.mux.Unlock()
return v
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, ret chan string, mapper UrlMapper) {
defer close(ret)
var _crawl func(string, int, Fetcher, chan string, UrlMapper)
_crawl = func(url string, depth int, fetcher Fetcher, ret chan string, mapper UrlMapper) {
if depth <= 0 {
return
}
if mapper.Get(url) != "" {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
//fmt.Println(err)
return
}
ret <- url
mapper.Set(url, body)
//fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
_crawl(u, depth-1, fetcher, ret, mapper)
}
}
_crawl(url, depth, fetcher, ret, mapper)
return
}
func main() {
mapper := UrlMapper{v: make(map[string]string)}
result := make(chan string)
go Crawl("http://golang.org/", 4, fetcher, result, mapper)
for s := range result {
fmt.Println(s)
}
}
// 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{
"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