Skip to content

Instantly share code, notes, and snippets.

@pjchender
Last active June 8, 2020 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjchender/99e3508f73a2b0b47d136bb9d26cf8b4 to your computer and use it in GitHub Desktop.
Save pjchender/99e3508f73a2b0b47d136bb9d26cf8b4 to your computer and use it in GitHub Desktop.
Channels and Go Routines
package main
import (
"fmt"
"net/http"
)
func main() {
links := []string{
"http://google.com",
"http://facebook.com",
"http://stackoverflow.com",
"http://golang.com",
"http://amazon.com",
}
c := make(chan string)
// 改成用匿名函式
for _, link := range links {
go func(link string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
c <- "might be down!"
return
}
fmt.Println(link, "is up!")
}(link)
}
// 只要 c 有東西就繼續跑
for message := range c {
fmt.Println(message)
}
close(c)
}
func checkLink(link string, c chan string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
c <- "might be down!"
return
}
fmt.Println(link, "is up!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment