Skip to content

Instantly share code, notes, and snippets.

@thaihuynhxyz
Last active January 10, 2022 06:01
Show Gist options
  • Save thaihuynhxyz/f40d4db98ce96d648e636ee371e37a6c to your computer and use it in GitHub Desktop.
Save thaihuynhxyz/f40d4db98ce96d648e636ee371e37a6c to your computer and use it in GitHub Desktop.
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, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
ch := make(chan result)
cache := SafeCache{v: make(map[string]*fakeResult)}
var crawl func(url string, depth int, fetcher Fetcher, ch chan result)
crawl = func(url string, depth int, fetcher Fetcher, ch chan result) {
if depth <= 0 {
return
}
cache.mu.Lock()
if it := cache.v[url]; it == nil {
body, urls, err := fetcher.Fetch(url)
if err != nil {
fmt.Println(err)
cache.mu.Unlock()
return
}
cache.v[url] = &fakeResult{body, urls}
cache.mu.Unlock()
ch <- result{url, body}
for _, u := range urls {
crawl(u, depth-1, fetcher, ch)
}
} else {
cache.mu.Unlock()
}
}
fetch := func(url string, depth int, fetcher Fetcher, ch chan result) {
defer close(ch)
crawl(url, depth, fetcher, ch)
}
go fetch(url, depth, fetcher, ch)
for result := range ch {
fmt.Printf("found: %s %q\n", result.url, result.body)
}
return
}
func main() {
Crawl("https://golang.org/", 4, fetcher)
}
// fakeFetcher is Fetcher that returns canned results.
type fakeFetcher map[string]*fakeResult
type fakeResult struct {
body string
urls []string
}
type result struct {
body string
url string
}
// SafeCache is safe to use concurrently.
type SafeCache struct {
mu sync.Mutex
v map[string]*fakeResult
}
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