我正在读《Go编程语言》一书,书中有一个例子演示了戈鲁廷泄漏
func mirroredQuery() string {
responses := make(chan string, 3)
go func() { responses <- request("asia.gopl.io") }()
go func() { responses <- request("europe.gopl.io") }()
go func() { responses <- request("americas.gopl.io") }()
return <-responses // return the quickest response
}
func request(hostname string) (response string) { /* ... */ }
我试图解决泄漏,并得到以下代码
func request(url string) string {
res, err := http.Get(url)
if err == nil {
body, err := io.ReadAll(res.Body)
if err == nil {
return string(body)
} else {
return err.Error()
}
} else {
return err.Error()
}
}
func getany() string {
rsp := make(chan string, 3)
done := make(chan struct{}, 3)
doRequest := func(url string) {
select {
case rsp <- request(url):
fmt.Printf("get %s\n", url)
done <- struct{}{}
case <- done:
fmt.Printf("stop %s\n", url)
return
}
}
go doRequest("http://google.com")
go doRequest("http://qq.com")
go doRequest("http://baidu.com")
return <-rsp
}
但似乎不能解决问题?有什么建议吗?
BIG阳
叮当猫咪
茅侃侃
相关分类