diff --git a/concurrency/iterator_error_handling/main.go b/concurrency/iterator_error_handling/main.go index 621717a..b33ba21 100644 --- a/concurrency/iterator_error_handling/main.go +++ b/concurrency/iterator_error_handling/main.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "net/http" "time" "github.com/davecgh/go-spew/spew" @@ -34,6 +35,8 @@ func concurrentFetch(urls []string) <-chan *FetchResult { } func main() { + v2() + return // mock the urls urls := []string{ "test1", @@ -63,3 +66,44 @@ func main() { // } fmt.Println("All my things are done") } + +type Result struct { + Error error + Response *http.Response +} + +func v2() { + checkStatus := func(done <-chan interface{}, urls ...string) <-chan Result { + results := make(chan Result) + go func() { + defer close(results) + for _, url := range urls { + var result Result + resp, err := http.Get(url) + result = Result{Error: err, Response: resp} + select { + + case <-done: + return + case results <- result: + } + } + }() + return results + } + done := make(chan interface{}) + errCount := 0 + urls := []string{"a", "https://www.google.com", "b", "c", "d"} + for result := range checkStatus(done, urls...) { + if result.Error != nil { + fmt.Printf("error: %v\n", result.Error) + errCount++ + if errCount >= 3 { + fmt.Println("Too many errors, breaking!") + break + } + continue + } + fmt.Printf("Response: %v\n", result.Response.Status) + } +}