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)
urls := []string{"https://www.baidu.com", "https://badhosts"}
for result := range checkStatus(done, urls...) {
if result.Error != nil {
fmt.Printf("Error: %v \n", result.Error)
continue
}
fmt.Printf("Response: %v \n", result.Response.Status)
}
}
程序输出如下,将Error返回给main goroutine进行处理。也就是返回给调用方进行处理。
有疑问加站长微信联系(非本文作者)