Advertisement
chikko

Untitled

Mar 24th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.81 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5. )
  6.  
  7. type Fetcher interface {
  8.     // Fetch returns the body of URL and
  9.     // a slice of URLs found on that page.
  10.     Fetch(url string) (body string, urls []string, err error)
  11. }
  12.  
  13. // Crawl uses fetcher to recursively crawl
  14. // pages starting with url, to a maximum of depth.
  15. func Crawl(url string, depth int, fetcher Fetcher) {
  16.     // TODO: Fetch URLs in parallel.
  17.     // TODO: Don't fetch the same URL twice.
  18.     // This implementation doesn't do either:
  19.     if depth <= 0 {
  20.         return
  21.     }
  22.     body, urls, err := fetcher.Fetch(url)
  23.     if err != nil {
  24.         fmt.Println(err)
  25.         return
  26.     }
  27.     fmt.Printf("found: %s %q\n", url, body)
  28.     for _, u := range urls {
  29.         Crawl(u, depth-1, fetcher)
  30.     }
  31.     return
  32. }
  33.  
  34. func main() {
  35.     Crawl("http://golang.org/", 4, fetcher)
  36. }
  37.  
  38. // fakeFetcher is Fetcher that returns canned results.
  39. type fakeFetcher map[string]*fakeResult
  40.  
  41. type fakeResult struct {
  42.     body string
  43.     urls []string
  44. }
  45.  
  46. func (f fakeFetcher) Fetch(url string) (string, []string, error) {
  47.     if res, ok := f[url]; ok {
  48.         return res.body, res.urls, nil
  49.     }
  50.     return "", nil, fmt.Errorf("not found: %s", url)
  51. }
  52.  
  53. // fetcher is a populated fakeFetcher.
  54. var fetcher = fakeFetcher{
  55.     "http://golang.org/": &fakeResult{
  56.         "The Go Programming Language",
  57.         []string{
  58.             "http://golang.org/pkg/",
  59.             "http://golang.org/cmd/",
  60.         },
  61.     },
  62.     "http://golang.org/pkg/": &fakeResult{
  63.         "Packages",
  64.         []string{
  65.             "http://golang.org/",
  66.             "http://golang.org/cmd/",
  67.             "http://golang.org/pkg/fmt/",
  68.             "http://golang.org/pkg/os/",
  69.         },
  70.     },
  71.     "http://golang.org/pkg/fmt/": &fakeResult{
  72.         "Package fmt",
  73.         []string{
  74.             "http://golang.org/",
  75.             "http://golang.org/pkg/",
  76.         },
  77.     },
  78.     "http://golang.org/pkg/os/": &fakeResult{
  79.         "Package os",
  80.         []string{
  81.             "http://golang.org/",
  82.             "http://golang.org/pkg/",
  83.         },
  84.     },
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement