Skip to content

Instantly share code, notes, and snippets.

@ryochack
Created January 12, 2012 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryochack/1601077 to your computer and use it in GitHub Desktop.
Save ryochack/1601077 to your computer and use it in GitHub Desktop.
"A Tour of Go" http://tour.golang.org/#70 共有リソースの排他がなく、問題あり
/*
* http://tour.golang.org/#70
* OR
* http://http://go-tour-jp.appspot.com/#69
*/
package main
import (
"os"
"fmt"
"runtime"
)
type dispResult struct {
url string
body string
}
var checkUrl map[string]int
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 os.Error)
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, ch chan dispResult, fetcher Fetcher) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
// URLのチェック回数を記録
checkUrl[url]++
// 2度目のチェックはしない
if checkUrl[url] > 1 {
return
}
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
ch <- dispResult{url, body}
for _, u := range urls {
go Crawl(u, depth-1, ch, fetcher)
}
return
}
func main() {
ch := make(chan dispResult)
checkUrl = make(map[string]int)
go Crawl("http://golang.org/", 4, ch, fetcher)
for {
if (runtime.Goroutines() == 1) {
break
} else {
select {
case v := <- ch:
fmt.Printf("found: %s %q\n", v.url, v.body)
}
}
}
}
// 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, os.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