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 關注
- 91 瀏覽
添加回答
舉報