1 回答
TA贡献1850条经验 获得超11个赞
当 触发错误时,您将立即返回,而不会从通道中删除阻塞项。Get
您可以在此处删除阻止项,也可以删除并实际在结构中存储指向 的指针(这样就可以从失败的请求中存储)。returnhttp.Responsenil
下面是使用第二种方法的 for 循环的代码,请注意,状态的打印现在处于一个中,因为它可能为 nil。else
// a struct to hold a pointer to the result from each request
// including an index which will be used for sorting the
// results after they come in
type result struct {
index int
res *http.Response
err error
}
// ...
// keen an index and loop through every url we will send a request to
for i, url := range urls {
// start a go routine with the index and url in a closure
go func(i int, url string) {
// this sends an empty struct into the semaphoreChan which
// is basically saying add one to the limit, but when the
// limit has been reached block until there is room
semaphoreChan <- struct{}{}
// send the request and put the response in a result struct
// along with the index so we can sort them later along with
// any error that might have occoured
res, err := http.Get(url)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(res.Status)
}
result := &result{i, res, err}
// now we can send the result struct through the resultsChan
resultsChan <- result
// once we're done it's we read from the semaphoreChan which
// has the effect of removing one from the limit and allowing
// another goroutine to start
<-semaphoreChan
}(i, url)
}
- 1 回答
- 0 关注
- 74 浏览
添加回答
举报