我根据以下示例创建了一个简单的通道来发出异步 HTTP 请求:
http://matt.aimonetti.net/posts/2012/11/27/real-life-concurrency-in-go/
一旦所有请求都完成,关闭通道的最佳模式是什么?
type HttpRequest struct {
url string
}
type HttpResponse struct {
request HttpRequest
response *http.Response
err error
}
func asyncHttpGets(requests []HttpRequest) {
ch := make(chan *HttpResponse)
for _, request := range requests {
go func(url string) {
resp, err := http.Get(url)
ch <- &HttpResponse{request, resp, err}
}(request.url)
}
for {
select {
case r := <-ch:
processResponse(r)
}
}
}
相关分类