package main
import (
"fmt"
"net/http"
)
type Result struct {
Error error
Response *http.Response
}
func main() {
checkStatus := func(done <-chan interface{},
urls ...string) <-chan Result {
results := make(chan Result)
go func() {
defer close(results)
for _, url := range urls {
resp, err := http.Get(url)
result := Result{
Error: err,
Response: resp,
}
select {
case <-done:
return
case results <- result:
}
}
}()
return results
}
done := make(chan interface{})
defer close(done)
errorCount := 0
urls := []string{"a", "https://www.baidu.com", "b", "c", "d", "https://badhosts"}
for result := range checkStatus(done, urls...) {
if result.Error != nil {
fmt.Printf("Error: %v \n", result.Error)
errorCount += 1
if errorCount >= 3 {
fmt.Println("Too many errors ,break")
break
}
continue
}
fmt.Printf("Response: %v \n", result.Response.Status)
}
}
程序输出如下,
image.png
网友评论