发布时间:2024-12-23 03:48:01
``` package main import ( "fmt" "net/http" "time" ) func checkWebsite(url string) { resp, err := http.Get(url) if err != nil { fmt.Printf("Error checking website %s: %s\n", url, err.Error()) return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { fmt.Printf("Website %s is up and running\n", url) } else { fmt.Printf("Website %s is down\n", url) } } func main() { urls := []string{"https://www.google.com", "https://www.github.com", "https://www.linkedin.com"} for _, url := range urls { go checkWebsite(url) } // 等待goroutine执行完毕 time.Sleep(5 * time.Second) } ```
在上述代码中,我们定义了一个`checkWebsite`函数,它会向给定的URL发送HTTP请求,并根据返回的状态码判断站点是否正常。然后,在`main`函数中,我们创建一个goroutine来并发执行`checkWebsite`函数,同时我们可以监控多个站点的状态。``` package main import ( "fmt" "net/http" "time" ) type Result struct { Url string Status int Message string } func checkWebsite(url string, c chan Result) { resp, err := http.Get(url) if err != nil { c <- Result{ Url: url, Status: http.StatusInternalServerError, Message: err.Error(), } return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { c <- Result{ Url: url, Status: http.StatusOK, Message: "Website is up and running", } } else { c <- Result{ Url: url, Status: resp.StatusCode, Message: fmt.Sprintf("Website returned status code %d", resp.StatusCode), } } } func main() { urls := []string{"https://www.google.com", "https://www.github.com", "https://www.linkedin.com"} results := make(chan Result) for _, url := range urls { go checkWebsite(url, results) } for i := 0; i < len(urls); i++ { result := <-results fmt.Printf("[%d] %s - %s\n", result.Status, result.Url, result.Message) } } ```
在上述代码中,我们定义了一个`Result`结构体,用于保存每个站点的监控结果。然后,我们在`checkWebsite`函数中,如果站点正常,将结果发送到channel;否则,也将结果发送到channel。在`main`函数中,我们创建一个channel来接收并打印监控结果。``` package main import ( "fmt" "net/http" "time" ) type Result struct { Url string Status int Message string } func checkWebsite(url string, c chan Result) { resp, err := http.Get(url) if err != nil { c <- Result{ Url: url, Status: http.StatusInternalServerError, Message: err.Error(), } return } defer resp.Body.Close() if resp.StatusCode == http.StatusOK { c <- Result{ Url: url, Status: http.StatusOK, Message: "Website is up and running", } } else { c <- Result{ Url: url, Status: resp.StatusCode, Message: fmt.Sprintf("Website returned status code %d", resp.StatusCode), } } } func main() { urls := []string{"https://www.google.com", "https://www.github.com", "https://www.linkedin.com"} results := make(chan Result) for _, url := range urls { go func(url string) { ticker := time.Tick(30 * time.Second) for range ticker { checkWebsite(url, results) } }(url) } for i := 0; i < len(urls)*3; i++ { result := <-results fmt.Printf("[%d] %s - %s\n", result.Status, result.Url, result.Message) } } ```
在上述代码中,我们使用匿名函数和`time.Tick`函数来实现每隔30秒执行一次监控任务。同时,我们增加了一个循环来接收并打印监控结果。这样,我们就可以实现定时监控和报警机制。