-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
handlers.go
99 lines (85 loc) · 2.47 KB
/
handlers.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
package main
import (
"bytes"
"strings"
"time"
"github.com/5HT2B/heartbeat/templates"
"github.com/valyala/fasthttp"
)
var (
apiPrefix = []byte("/api/")
cssPrefix = []byte("/css/")
icoSuffix = []byte(".ico")
pngSuffix = []byte(".png")
gitRepo = "https://github.com/5HT2B/heartbeat" // set in .env
cssHandler = fasthttp.FSHandler("www", 1)
imgHandler = fasthttp.FSHandler("www", 0)
)
func RequestHandler(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set(fasthttp.HeaderServer, serverName)
path := ctx.Path()
pathStr := string(path)
if pathStr != "/" {
pathStr = strings.TrimSuffix(pathStr, "/")
}
switch {
case bytes.HasPrefix(path, apiPrefix):
ApiHandler(ctx, pathStr)
case bytes.HasPrefix(path, cssPrefix):
cssHandler(ctx)
case bytes.HasSuffix(path, icoSuffix), bytes.HasSuffix(path, pngSuffix):
imgHandler(ctx)
default:
heartbeatStats.TotalVisits += 1
heartbeatStats.TotalVisitsFormatted = FormattedNum(heartbeatStats.TotalVisits)
ctx.Response.Header.Set(fasthttp.HeaderContentType, "text/html; charset=utf-8")
switch pathStr {
case "/":
MainPageHandler(ctx)
case "/privacy":
PrivacyPolicyPageHandler(ctx)
case "/stats":
StatsPageHandler(ctx)
default:
ErrorNotFound(ctx, false)
}
}
}
func MainPageHandler(ctx *fasthttp.RequestCtx) {
p := getMainPage()
templates.WritePageTemplate(ctx, p)
}
func PrivacyPolicyPageHandler(ctx *fasthttp.RequestCtx) {
p := &templates.PrivacyPolicyPage{
ServerName: serverName,
}
templates.WritePageTemplate(ctx, p)
}
func StatsPageHandler(ctx *fasthttp.RequestCtx) {
UpdateUptime()
UpdateNumDevices()
p := &templates.StatsPage{
TotalBeats: heartbeatStats.TotalBeatsFormatted,
TotalDevices: heartbeatStats.TotalDevicesFormatted,
TotalVisits: heartbeatStats.TotalVisitsFormatted,
TotalUptime: heartbeatStats.TotalUptimeFormatted,
ServerName: serverName,
}
templates.WritePageTemplate(ctx, p)
}
func getMainPage() *templates.MainPage {
currentTime := time.Now()
lastBeat := GetLastBeat()
UpdateLastBeatFmtV(lastBeat, currentTime)
page := &templates.MainPage{
LastSeen: LastSeen(), // date last seen
TimeDifference: heartbeatStats.LastBeatFormatted, // relative time to last seen
MissingBeat: LongestAbsence(), // longest absence
TotalBeats: heartbeatStats.TotalBeatsFormatted,
CurrentTime: currentTime.Format(timeFormat),
GitHash: gitCommitHash,
GitRepo: gitRepo,
ServerName: serverName,
}
return page
}