Created
September 2, 2018 03:05
-
-
Save geowa4/5424d19f1f6bc19f4c98f4574d3d94ca to your computer and use it in GitHub Desktop.
My solution to the Tour of Go Web Crawler (Hint: read the sync package docs at https://golang.org/pkg/sync/.)
This file contains 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) | |
} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url. | |
func Crawl(url string, fetcher Fetcher, visited *sync.Map, wg *sync.WaitGroup) { | |
defer wg.Done() | |
if _, ok := visited.Load(url); ok { | |
//fmt.Printf("skipping: %s\n", url) | |
return | |
} | |
body, foundUrls, err := fetcher.Fetch(url) | |
visited.Store(url, true) | |
if err != nil { | |
fmt.Println(err) | |
return | |
} | |
fmt.Printf("found: %s %q\n", url, body) | |
for _, newUrl := range foundUrls { | |
wg.Add(1) | |
go Crawl(newUrl, fetcher, visited, wg) | |
} | |
} | |
func main() { | |
var visited sync.Map | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go Crawl("https://golang.org/", fetcher, &visited, &wg) | |
wg.Wait() | |
} | |
// 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{ | |
"https://golang.org/": &fakeResult{ | |
"The Go Programming Language", | |
[]string{ | |
"https://golang.org/pkg/", | |
"https://golang.org/cmd/", | |
}, | |
}, | |
"https://golang.org/pkg/": &fakeResult{ | |
"Packages", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/cmd/", | |
"https://golang.org/pkg/fmt/", | |
"https://golang.org/pkg/os/", | |
}, | |
}, | |
"https://golang.org/pkg/fmt/": &fakeResult{ | |
"Package fmt", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
"https://golang.org/pkg/os/": &fakeResult{ | |
"Package os", | |
[]string{ | |
"https://golang.org/", | |
"https://golang.org/pkg/", | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment