去尝试解答Go Tour的第71题
问题
改良原有的网络爬虫是任务的挑战。
-
- 平行処理でクロールする
- クロール済みのページはクロールしない
回答: 只需要一种选择的话,用汉语自然地改写以下内容:
这样可以吗……感觉还可以写得更好一些。
重点是
-
- fetch済かどうかをChennel(holder)で管理している
- 子goroutineが終わるまで親のプロセスが待つためのChannel(done)を用意する
package main
import (
"fmt"
"time"
)
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) {
fmt.Printf("start. depth=%d, url=%s\n", depth, url)
if depth <= 0 {
return
}
history := <-holder
if _, ok := history[url]; ok {
fmt.Printf("already fetched: %s \n", url)
holder <- history
return
}
history[url] = url
holder <- history
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
done := make(chan bool)
for _, u := range urls {
go func(url string) {
Crawl(url, depth-1, fetcher)
done <- true
}(u)
}
for _, _ = range urls {
<-done
}
fmt.Printf("end. depth=%d, url=%s\n", depth, url)
return
}
var holder chan fetchHistory
func init() {
holder = make(chan fetchHistory, 1)
holder <- fetchHistory(make(map[string]string))
}
func main() {
Crawl("http://golang.org/", 4, fetcher)
fmt.Println("finish!!")
}
var historyHolder chan fetchHistory
type fetchHistory map[string]string
// 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
}
// timeout
time.Sleep(1000 * time.Millisecond)
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/",
},
},
}