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