package main
import (
"fmt"
"net/http"
)
func main() {
checkStatus := func(done <-chan interface{},
urls ...string) <-chan *http.Response {
responses := make(chan *http.Response)
go func() {
defer close(responses)
for _, url := range urls {
resp, err := http.Get(url)
if err != nil {
fmt.Println(err)
continue
}
select {
case <-done:
return
case responses <- resp:
}
}
}()
return responses
}
done := make(chan interface{})
defer close(done)
urls := []string{"https://www.baidu.com", "https://badhost"}
for response := range checkStatus(done, urls...) {
fmt.Printf("Response %v\n", response.Status)
}
}
程序输出如下,
有疑问加站长微信联系(非本文作者)