-
-
Save pjchender/99e3508f73a2b0b47d136bb9d26cf8b4 to your computer and use it in GitHub Desktop.
Channels and Go Routines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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