monitor.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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 OptionalEnvString `yaml:"url"`
  44. IconUrl string `yaml:"icon"`
  45. SameTab bool `yaml:"same-tab"`
  46. Status *feed.SiteStatus `yaml:"-"`
  47. StatusText string `yaml:"-"`
  48. StatusStyle string `yaml:"-"`
  49. } `yaml:"sites"`
  50. Style string `yaml:"style"`
  51. }
  52. func (widget *Monitor) Initialize() error {
  53. widget.withTitle("Monitor").withCacheDuration(5 * time.Minute)
  54. return nil
  55. }
  56. func (widget *Monitor) Update(ctx context.Context) {
  57. requests := make([]*http.Request, len(widget.Sites))
  58. for i := range widget.Sites {
  59. request, err := http.NewRequest("GET", string(widget.Sites[i].Url), nil)
  60. if err != nil {
  61. message := fmt.Errorf("failed to create http request for %s: %s", widget.Sites[i].Url, err)
  62. widget.withNotice(message)
  63. continue
  64. }
  65. requests[i] = request
  66. }
  67. statuses, err := feed.FetchStatusesForRequests(requests)
  68. if !widget.canContinueUpdateAfterHandlingErr(err) {
  69. return
  70. }
  71. for i := range widget.Sites {
  72. site := &widget.Sites[i]
  73. status := &statuses[i]
  74. site.Status = status
  75. if !status.TimedOut {
  76. site.StatusText = statusCodeToText(status.Code)
  77. site.StatusStyle = statusCodeToStyle(status.Code)
  78. }
  79. }
  80. }
  81. func (widget *Monitor) Render() template.HTML {
  82. return widget.render(widget, assets.MonitorTemplate)
  83. }