Website Status Checker

Printing Site Status

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",
}
for _, link := range links {
checkLink(link)
}
}
func checkLink(link string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
}
fmt.Println(link, "is up!")
}

Serial Link Checking

Go Routines



Theory of Go Rountines





Channels
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",
}
for _, link := range links {
go checkLink(link)
}
}
func checkLink(link string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
}
fmt.Println(link, "is up!")
}



Channel Implementation
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 checkLink(link, c)
}
}
func checkLink(link string, c chan string) {
_, err := http.Get(link)
if err != nil {
fmt.Println(link, "might be down!")
}
fmt.Println(link, "is up!")
}

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 checkLink(link, c)
}
fmt.Println(<-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 I think"
return
}
fmt.Println(link, "is up!")
}

Blocking Channels


Receiving Messages
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 checkLink(link, c)
}
for i := 0; i < len(links); i++ {
fmt.Println(<-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 I think"
return
}
fmt.Println(link, "is up!")
c <- "Yep its up"
}

Repeating Routines
Alternative Loop Syntax
Sleeping a Routine
Function Literals
Channels Gotcha






这篇文章展示了如何使用Go语言进行网站状态检查。首先,它演示了一个简单的串行检查,然后通过引入goroutines实现并发检查以提高效率。接着,通过channels在goroutines间传递信息,确保了对检查结果的有效管理,包括处理可能的错误和确认网站是否在线。最后,讨论了阻塞channels、接收消息以及如何重复运行goroutines的策略。
2199

被折叠的 条评论
为什么被折叠?



