monitor.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. package widget
  2. import (
  3. "context"
  4. "fmt"
  5. "html/template"
  6. "net/http"
  7. "strconv"
  8. "time"
  9. "github.com/glanceapp/glance/internal/assets"
  10. "github.com/glanceapp/glance/internal/feed"
  11. )
  12. func statusCodeToText(status int) string {
  13. if status == 200 {
  14. return "OK"
  15. }
  16. if status == 404 {
  17. return "Not Found"
  18. }
  19. if status == 403 {
  20. return "Forbidden"
  21. }
  22. if status == 401 {
  23. return "Unauthorized"
  24. }
  25. if status >= 400 {
  26. return "Client Error"
  27. }
  28. if status >= 500 {
  29. return "Server Error"
  30. }
  31. return strconv.Itoa(status)
  32. }
  33. func statusCodeToStyle(status int) string {
  34. if status == 200 {
  35. return "good"
  36. }
  37. return "bad"
  38. }
  39. type Monitor struct {
  40. widgetBase `yaml:",inline"`
  41. Sites []struct {
  42. Title string `yaml:"title"`
  43. Url string `yaml:"url"`
  44. IconUrl string `yaml:"icon"`
  45. Status *feed.SiteStatus `yaml:"-"`
  46. StatusText string `yaml:"-"`
  47. StatusStyle string `yaml:"-"`
  48. } `yaml:"sites"`
  49. }
  50. func (widget *Monitor) Initialize() error {
  51. widget.withTitle("Monitor").withCacheDuration(5 * time.Minute)
  52. return nil
  53. }
  54. func (widget *Monitor) Update(ctx context.Context) {
  55. requests := make([]*http.Request, len(widget.Sites))
  56. for i := range widget.Sites {
  57. request, err := http.NewRequest("GET", widget.Sites[i].Url, nil)
  58. if err != nil {
  59. message := fmt.Errorf("failed to create http request for %s: %s", widget.Sites[i].Url, err)
  60. widget.withNotice(message)
  61. continue
  62. }
  63. requests[i] = request
  64. }
  65. statuses, err := feed.FetchStatusesForRequests(requests)
  66. if !widget.canContinueUpdateAfterHandlingErr(err) {
  67. return
  68. }
  69. for i := range widget.Sites {
  70. site := &widget.Sites[i]
  71. status := &statuses[i]
  72. site.Status = status
  73. if !status.TimedOut {
  74. site.StatusText = statusCodeToText(status.Code)
  75. site.StatusStyle = statusCodeToStyle(status.Code)
  76. }
  77. }
  78. }
  79. func (widget *Monitor) Render() template.HTML {
  80. return widget.render(widget, assets.MonitorTemplate)
  81. }