123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- package service
-
- import (
- "fmt"
- "net/http"
- "strings"
- "time"
-
- "git.links123.net/links123.com/monitor_status/config"
- "git.links123.net/links123.com/monitor_status/service/notice"
- "git.links123.net/links123.com/monitor_status/service/store/cache"
- )
-
- var httpClient = &http.Client{
- Timeout: 10 * time.Second,
- }
-
- func Monitor() error {
- urls := strings.Split(config.C.Monitor.URLs, ";")
- for {
- monitorStep(urls)
-
- time.Sleep(10 * time.Second) //10s 间隔
- }
- return nil
- }
-
- func monitorStep(urls []string) {
- for _, url := range urls {
- err := monitorURL(url)
- if cache.CheckMonitor(url, err) {
- if err != nil {
- notice.SendEmailBySMTP("url error", config.C.Notice.Emails, err.Error(), false)
- } else {
- notice.SendEmailBySMTP("url return ok", config.C.Notice.Emails, "return ok", false)
- }
- }
- }
- }
-
- func monitorURL(url string) error {
- startTime := time.Now()
- resp, err := httpClient.Get(url)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
- if resp.StatusCode != http.StatusOK {
- return fmt.Errorf("status code:%d url:%s", resp.StatusCode, url)
- }
- useTime := int64(time.Now().Sub(startTime) / time.Millisecond)
- if useTime > config.C.Monitor.Timeout {
- return fmt.Errorf("timeout url:%s,millisecond:%d", url, useTime)
- }
- return nil
- }
|