http urls monitor.

service.go 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package service
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strings"
  6. "time"
  7. "git.links123.net/links123.com/monitor_status/config"
  8. "git.links123.net/links123.com/monitor_status/service/notice"
  9. "git.links123.net/links123.com/monitor_status/service/store/cache"
  10. )
  11. var httpClient = &http.Client{
  12. Timeout: 10 * time.Second,
  13. }
  14. func Monitor() error {
  15. urls := strings.Split(config.C.Monitor.URLs, ";")
  16. for {
  17. monitorStep(urls)
  18. time.Sleep(10 * time.Second) //10s 间隔
  19. }
  20. return nil
  21. }
  22. func monitorStep(urls []string) {
  23. for _, url := range urls {
  24. err := monitorURL(url)
  25. if cache.CheckMonitor(url, err) {
  26. if err != nil {
  27. notice.SendEmailBySMTP("url error", config.C.Notice.Emails, err.Error(), false)
  28. } else {
  29. notice.SendEmailBySMTP("url return ok", config.C.Notice.Emails, "return ok", false)
  30. }
  31. }
  32. }
  33. }
  34. func monitorURL(url string) error {
  35. startTime := time.Now()
  36. resp, err := httpClient.Get(url)
  37. if err != nil {
  38. return err
  39. }
  40. defer resp.Body.Close()
  41. if resp.StatusCode != http.StatusOK {
  42. return fmt.Errorf("status code:%d url:%s", resp.StatusCode, url)
  43. }
  44. useTime := int64(time.Now().Sub(startTime) / time.Millisecond)
  45. if useTime > config.C.Monitor.Timeout {
  46. return fmt.Errorf("timeout url:%s,millisecond:%d", url, useTime)
  47. }
  48. return nil
  49. }