[Go语言]我的第十一个Go语言程序
2016-08-02 21:24
483 查看
Exercise: Web Crawler
In this exercise you'll use Go's concurrency features to parallelize a web crawler.Modify the
Crawlfunction to fetch URLs in parallel without fetching the same URL twice.
Hint: you can keep a cache of the URLs that have been fetched on a map, but maps alone are not safe for concurrent use!
package main
import (
"fmt"
"sync"
"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)
}
type Fetched struct {
v map[string]bool
mux sync.Mutex
}
var fetched = Fetched{v : make(map[string]bool)}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
if depth <= 0 {
return
}
fetched.mux.Lock()
defer fetched.mux.Unlock()
if _, ok := fetched.v[url]; !ok {
body, urls, err := fetcher.Fetch(url)
fetched.v[url] = true;
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
go Crawl(u, depth-1, fetcher)
}
}
return
}
func main() {
Crawl("http://golang.org/", 4, fetcher)
time.Sleep(time.Second)
}
// 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/",
},
},
}
相关文章推荐
- Go语言日趋成熟 运行速度接近C语言实现程序
- go语言 -并行程序 wordcount
- 创建第一个Go语言程序Hello,Go!
- go语言实现的目录共享程序
- 关于GDB调试go语言程序中出现 os.Args无法打印的问题
- Go语言学习札记——第三章 Go基本的程序设计结构(1)
- 在Go语言程序中使用gojson来解析JSON格式文件
- Go语言程序的状态监控 via 达达
- go语言编写,简单聊天室程序 1
- 使用GO语言开发 Redis数据监控程序
- Goclipse中运行Go语言程序的配置
- go语言编写Web程序
- 我的第一个比较实用的GO语言程序
- Go语言程序的状态监控
- Go 语言中实现优雅的停止程序
- 在go语言中统计程序执行时间
- Eclipse里编写Go语言程序
- Sublim Text 开发Go语言程序
- Windows下使用go语言写程序安装配置实例
- Go语言监控文件变化小程序.