Skip to content

Instantly share code, notes, and snippets.

@kkabdol
Created April 22, 2016 02:11
Show Gist options
  • Select an option

  • Save kkabdol/0252073b246cfb52960af4fe41155b18 to your computer and use it in GitHub Desktop.

Select an option

Save kkabdol/0252073b246cfb52960af4fe41155b18 to your computer and use it in GitHub Desktop.
go language exercise
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 SafeCounter struct {
v map[string]bool
chu chan string
chb chan string
mux sync.Mutex
}
// Crawl uses fetcher to recursively crawl
// pages starting with url, to a maximum of depth.
func (c *SafeCounter) Crawl(url string, depth int, fetcher Fetcher) {
c.mux.Lock()
defer c.mux.Unlock()
// 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)
if err != nil {
fmt.Println(err)
return
}
if c.v[url] != true {
c.chu <- url
c.chb <- body
c.v[url] = true;
}
for _, u := range urls {
go c.Crawl(u, depth-1, fetcher)
}
return
}
func main() {
c := SafeCounter{v: make(map[string]bool), chu: make(chan string), chb: make(chan string)}
go c.Crawl("http://golang.org/", 4, fetcher)
for i := range c.chu {
fmt.Printf("%s %q\n", i, <-c.chb)
}
}
// 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{
"http://golang.org/": &fakeResult{
"The Go Programming Language",
[]string{
"http://golang.org/pkg/",
"http://golang.org/cmd/",
},
},
"http://golang.org/pkg/": &fakeResult{
"Packages",
[]string{
"http://golang.org/",
"http://golang.org/cmd/",
"http://golang.org/pkg/fmt/",
"http://golang.org/pkg/os/",
},
},
"http://golang.org/pkg/fmt/": &fakeResult{
"Package fmt",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
"http://golang.org/pkg/os/": &fakeResult{
"Package os",
[]string{
"http://golang.org/",
"http://golang.org/pkg/",
},
},
}
@kkabdol
Copy link
Author

kkabdol commented Apr 22, 2016

fatal error: all goroutines are asleep - deadlock!

need to solve it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment