Skip to content

Instantly share code, notes, and snippets.

@hsnice16
Created August 6, 2024 17:49
Show Gist options
  • Save hsnice16/f0ce3ab879e513ad5fc4ef4bb1315d1a to your computer and use it in GitHub Desktop.
Save hsnice16/f0ce3ab879e513ad5fc4ef4bb1315d1a 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)
}
type Cache struct {
mu sync.Mutex
fetchedUrls map[string]bool
}
var end = make(chan int)
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, cache *Cache) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
body, urls, err := fetcher.Fetch(url)
(*cache).mu.Lock()
(*cache).fetchedUrls[url] = true
(*cache).mu.Unlock()
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, url := range urls {
if _, ok := (*cache).fetchedUrls[url]; ok {
continue
}
go func() {
end <- 1
Crawl(url, depth-1, fetcher, cache)
}()
<-end
}
return
}
func main() {
cache := Cache{
fetchedUrls: make(map[string]bool),
}
Crawl("https://golang.org/", 4, fetcher, &cache)
}
// 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