mirror of
https://github.com/crazybber/awesome-patterns.git
synced 2024-11-28 15:56:04 +03:00
v2 handle error
This commit is contained in:
parent
10e9ef931b
commit
92522f33ae
@ -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)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user