Last active
December 7, 2024 22:01
-
-
Save SaoYan/32cf28b4689d3d9b077cc96d105a31df to your computer and use it in GitHub Desktop.
A Tour of Go Exercise: Web Crawler
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" | |
) | |
/* | |
This solution uses channels to force each gorountines to wait for its child gorountines to exit. | |
*/ | |
type SafeCounter struct { | |
v map[string]bool | |
mux sync.Mutex | |
} | |
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 cnt SafeCounter = SafeCounter{v: make(map[string]bool)} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher, exit chan bool) { | |
// Fetch URLs in parallel. | |
// Don't fetch the same URL twice. | |
if depth <= 0 { | |
exit <- true | |
return | |
} | |
cnt.mux.Lock() | |
_, ok := cnt.v[url] | |
if ok == false { | |
cnt.v[url] = true | |
cnt.mux.Unlock() | |
} else { | |
exit <- true | |
cnt.mux.Unlock() | |
return | |
} | |
body, urls, err := fetcher.Fetch(url) | |
if err != nil { | |
fmt.Println(err) | |
exit <- true | |
return | |
} | |
fmt.Printf("found: %s %q\n", url, body) | |
e := make(chan bool) | |
for _, u := range urls { | |
go Crawl(u, depth-1, fetcher, e) | |
} | |
// wait for all child gorountines to exit | |
for i := 0; i < len(urls); i++ { | |
<-e | |
} | |
exit <- true | |
} | |
func main() { | |
exit := make(chan bool) | |
go Crawl("https://golang.org/", 4, fetcher, exit) | |
<-exit | |
} | |
// 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/", | |
}, | |
}, | |
} |
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" | |
) | |
/* | |
This solution uses WaitGroup to force each gorountines to wait for its child gorountines to exit. | |
*/ | |
type SafeCounter struct { | |
v map[string]bool | |
mux sync.Mutex | |
} | |
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 cnt SafeCounter = SafeCounter{v: make(map[string]bool)} | |
// Crawl uses fetcher to recursively crawl | |
// pages starting with url, to a maximum of depth. | |
func Crawl(url string, depth int, fetcher Fetcher, wg *sync.WaitGroup) { | |
// Fetch URLs in parallel. | |
// Don't fetch the same URL twice. | |
if depth <= 0 { | |
wg.Done() | |
return | |
} | |
cnt.mux.Lock() | |
_, ok := cnt.v[url] | |
if ok == false { | |
cnt.v[url] = true | |
cnt.mux.Unlock() | |
} else { | |
wg.Done() | |
cnt.mux.Unlock() | |
return | |
} | |
body, urls, err := fetcher.Fetch(url) | |
if err != nil { | |
fmt.Println(err) | |
wg.Done() | |
return | |
} | |
fmt.Printf("found: %s %q\n", url, body) | |
var wg_ sync.WaitGroup | |
for _, u := range urls { | |
wg_.Add(1) | |
go Crawl(u, depth-1, fetcher, &wg_) | |
} | |
wg_.Wait() | |
wg.Done() | |
} | |
func main() { | |
var wg sync.WaitGroup | |
go Crawl("https://golang.org/", 4, fetcher, &wg) | |
wg.Add(1) | |
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/", | |
}, | |
}, | |
} |
This is what I have done
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/",
},
},
}
You just need to the semantics of defer. No need WaitGroup. No need Channel.
package main
import (
"fmt"
"sync"
"time"
)
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 UrlCache struct {
mu sync.Mutex
cache map[string]string
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func Crawl(url string, depth int, fetcher Fetcher, urlCache *UrlCache) {
// TODO: Fetch URLs in parallel.
// TODO: Don't fetch the same URL twice.
// This implementation doesn't do either:
if depth <= 0 {
return
}
urlCache.mu.Lock()
_, ok := urlCache.cache[url]
defer urlCache.mu.Unlock()
if ok {
return
}
body, urls, err := fetcher.Fetch(url)
urlCache.cache[url] = url
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("found: %s %q\n", url, body)
for _, u := range urls {
go Crawl(u, depth-1, fetcher, urlCache)
}
return
}
func main() {
cache := UrlCache{cache: make(map[string]string)}
go Crawl("https://golang.org/", 4, fetcher, &cache)
time.Sleep(time.Second)
}
// 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
re: https://gist.github.com/SaoYan/32cf28b4689d3d9b077cc96d105a31df?permalink_comment_id=4667391#gistcomment-4667391
there is a race condition in get/set.. think about it