generated from datumforge/go-template
-
Notifications
You must be signed in to change notification settings - Fork 7
/
readiness.go
57 lines (45 loc) · 1.31 KB
/
readiness.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
package handlers
import (
"context"
"net/http"
echo "github.com/datumforge/echox"
)
// StatusReply returns server status
type StatusReply struct {
Status map[string]string `json:"status"`
}
// CheckFunc is a function that can be used to check the status of a service
type CheckFunc func(ctx context.Context) error
type Checks struct {
checks map[string]CheckFunc
}
// AddReadinessCheck will accept a function to be ran during calls to /readyz
// These functions should accept a context and only return an error. When adding
// a readiness check a name is also provided, this name will be used when returning
// the state of all the checks
func (h *Handler) AddReadinessCheck(name string, f CheckFunc) {
// if this is null, create the struct before trying to add
if h.ReadyChecks.checks == nil {
h.ReadyChecks.checks = map[string]CheckFunc{}
}
h.ReadyChecks.checks[name] = f
}
func (c *Checks) ReadyHandler(ctx echo.Context) error {
failed := false
status := map[string]string{}
for name, check := range c.checks {
if err := check(ctx.Request().Context()); err != nil {
failed = true
status[name] = err.Error()
} else {
status[name] = "OK"
}
}
if failed {
return ctx.JSON(http.StatusServiceUnavailable, status)
}
out := &StatusReply{
Status: status,
}
return ctx.JSON(http.StatusOK, out)
}