-
Notifications
You must be signed in to change notification settings - Fork 1
/
route.go
93 lines (75 loc) · 1.96 KB
/
route.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
package stress
import (
"crypto/tls"
"encoding/json"
"net/http"
"time"
)
type RouteHelp struct {
Pattern string
Help string
}
type CheckData struct {
Version string `json:"version"`
Start time.Time `json:"start"`
UptimeSeconds float64 `json:"uptime_seconds"`
}
func MakeCheckData(version string) CheckData {
now := time.Now()
return CheckData{
Version: version,
Start: now,
UptimeSeconds: 0,
}
}
type Routes []*Route
type ServeData struct {
routeList []RouteHelp
checkData CheckData
}
func NewServeData(version string) *ServeData {
return &ServeData{
checkData: MakeCheckData(version),
}
}
type RouteFunc func(pattern string, handler HandlerFunc, optHelp ...string) *Route
func GenerateMakeRoute(serveData *ServeData) RouteFunc {
return func(pattern string, handler HandlerFunc, optHelp ...string) *Route {
help := ""
if len(optHelp) > 0 {
help = optHelp[0]
}
serveData.routeList = append(serveData.routeList, RouteHelp{
Pattern: pattern,
Help: help,
})
return NewRoute(pattern, handler)
}
}
func MarshalIndent(v interface{}) []byte {
dat, err := json.MarshalIndent(v, "", "\t")
CheckError(err)
return dat
}
func Serve(addr string, appRoutes Routes, serveData *ServeData, tlsConfig *tls.Config) {
makeRoute := GenerateMakeRoute(serveData)
commonRoutes := Routes{
makeRoute("^/check$", func(w http.ResponseWriter, r *http.Request, match Match) {
dat := serveData.checkData
dat.UptimeSeconds = time.Now().Sub(dat.Start).Seconds()
ServeJSON(w, http.StatusOK, MarshalIndent(dat))
}, "Service version and uptime"),
makeRoute("^/aux/help$", func(w http.ResponseWriter, r *http.Request, match Match) {
b := MarshalIndent(serveData.routeList)
ServeJSON(w, http.StatusOK, b)
}, "Show help about all routes/endpoints"),
}
var routes Routes
for _, r := range []Routes{
appRoutes,
commonRoutes,
} {
routes = append(routes, r...)
}
ListenAndServe(addr, routes, tlsConfig)
}