我正在使用 Golang,我创建了这个小应用程序来使用 goroutine 进行多个并发 api 调用。
当应用程序工作时,调用完成后,应用程序会卡住,这是有道理的,因为它无法退出范围c循环,因为通道未关闭。
我不知道在这种模式下哪里可以更好地关闭通道。
package main
import "fmt"
import "net/http"
func main() {
links := []string{
"https://github.com/fabpot",
"https://github.com/andrew",
"https://github.com/taylorotwell",
"https://github.com/egoist",
"https://github.com/HugoGiraudel",
}
checkUrls(links)
}
func checkUrls(urls []string) {
c := make(chan string)
for _, link := range urls {
go checkUrl(link, c)
}
for msg := range c {
fmt.Println(msg)
}
close(c) //this won't get hit
}
func checkUrl(url string, c chan string) {
_, err := http.Get(url)
if err != nil {
c <- "We could not reach:" + url
} else {
c <- "Success reaching the website:" + url
}
}
jeck猫
一只斗牛犬
相关分类