I use multiple goroutines to run the task, and when one of them is done, return and close the channel, that will cause an panic:send on closed channel.
See code:
func fetch(urls []string) *http.Response {
ch := make(chan *http.Response)
defer close(ch)
for _, url := range urls {
go func() {
resp, err := http.Get(url)
if err == nil {
ch <- resp
}
}()
}
return <-ch
}
If don't close the channel, there is no problem, but I don't think so good, so is there any elegant solution?
Thanks for all the answers,here is my final code:
func fetch(urls []string) *http.Response {
var wg sync.WaitGroup
ch := make(chan *http.Response)
wg.Add(len(urls))
for _, url := range urls {
go func(url string) {
defer wg.Done()
resp, err := http.Get(url)
if err == nil {
ch <- resp
}
}(url)
}
go func() {
wg.Wait()
close(ch)
}()
return <-ch
}