Last active
October 22, 2016 18:12
-
-
Save nmiano1111/6e11f966a994622c0fb79df89f349aed to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| var used = make(map[string]int) | |
| var mux = sync.Mutex{} | |
| // Crawl uses fetcher to recursively crawl | |
| // pages starting with url, to a maximum of depth. | |
| func Crawl(url string, depth int, fetcher Fetcher, c chan string) { | |
| defer close(c) | |
| if depth <= 0 { | |
| return | |
| } | |
| body, urls, err := fetcher.Fetch(url) | |
| if err != nil { | |
| fmt.Println(err) | |
| return | |
| } | |
| if used[url] == 0 { | |
| mux.Lock() | |
| used[url]++ | |
| mux.Unlock() | |
| c <- fmt.Sprintf("found: %s %q\n", url, body) | |
| } | |
| rs := make([]chan string, len(urls)) | |
| for i, u := range urls { | |
| rs[i] = make(chan string) | |
| go Crawl(u, depth-1, fetcher, rs[i]) | |
| } | |
| for i := range rs { | |
| for s := range rs[i] { | |
| c <- s | |
| } | |
| } | |
| return | |
| } | |
| func main() { | |
| ch := make(chan string) | |
| go Crawl("http://golang.org/", 4, fetcher, ch) | |
| for r := range ch { | |
| fmt.Print(r) | |
| } | |
| } | |
| // 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/", | |
| }, | |
| }, | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from https://tour.golang.org/concurrency/10