1 回答

TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
當(dāng) 觸發(fā)錯(cuò)誤時(shí),您將立即返回,而不會從通道中刪除阻塞項(xiàng)。Get
您可以在此處刪除阻止項(xiàng),也可以刪除并實(shí)際在結(jié)構(gòu)中存儲指向 的指針(這樣就可以從失敗的請求中存儲)。returnhttp.Responsenil
下面是使用第二種方法的 for 循環(huán)的代碼,請注意,狀態(tài)的打印現(xiàn)在處于一個(gè)中,因?yàn)樗赡転?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 關(guān)注
- 93 瀏覽
添加回答
舉報(bào)