Skip to content

Instantly share code, notes, and snippets.

@huahuayu
Created January 23, 2019 05:26
Show Gist options
  • Save huahuayu/317abd14ac2062a163d58c098fdef002 to your computer and use it in GitHub Desktop.
Save huahuayu/317abd14ac2062a163d58c098fdef002 to your computer and use it in GitHub Desktop.
[unbuffered channel]使用unbuffered channel goroutine轮询网站 #goroutine #channel #go
package unbuffered
import (
"fmt"
"net/http"
"time"
)
func main() {
links := []string{
"http://baidu.com",
"http://qq.com",
"http://taobao.com",
"http://jd.com",
"http://z.cn",
}
c := make(chan string)
for _, link := range links {
go func(link string) {
checkLink(link, c)
}(link)
}
for l := range c {
go func(link string) {
time.Sleep(5 * time.Second)
checkLink(link, c)
}(l)
}
}
func checkLink(link string, c chan string) {
_, err := http.Get(link)
defer func() { c <- link }()
if err != nil {
fmt.Println(link, "might be down!")
} else {
fmt.Println(link, "is up!")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment