-
Notifications
You must be signed in to change notification settings - Fork 2
/
health.go
39 lines (30 loc) · 957 Bytes
/
health.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
package tel
import (
"encoding/json"
"net/http"
health "github.com/d7561985/tel/v2/monitoring/heallth"
)
type HealthHandler struct {
health.CompositeChecker
}
// NewHealthHandler returns a new Handler
func NewHealthHandler() *HealthHandler {
return &HealthHandler{}
}
// ServeHTTP returns a json encoded health
// set the status to http.StatusServiceUnavailable if the check is down
func (h *HealthHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
checker := h.CompositeChecker.Check()
body, err := json.Marshal(checker)
if err != nil {
FromCtx(r.Context()).Error("health check encode failed", Error(err))
}
if checker.Is(health.Down) {
w.WriteHeader(http.StatusServiceUnavailable)
FromCtx(r.Context()).Error("health", String("body", string(body)))
}
if _, err = w.Write(body); err != nil {
FromCtx(r.Context()).Error("health check encode failed", Error(err))
}
}