-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
83 lines (64 loc) · 1.75 KB
/
http.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
package http
import (
"net/http"
"github.com/alexfalkowski/go-health/subscriber"
"github.com/alexfalkowski/go-service/env"
"github.com/alexfalkowski/go-service/marshaller"
sh "github.com/alexfalkowski/go-service/net/http"
"go.uber.org/fx"
)
const (
serving = "SERVING"
notServing = "NOT_SERVING"
)
// RegisterParams health for HTTP.
type RegisterParams struct {
fx.In
Mux sh.ServeMux
Health *HealthObserver
Liveness *LivenessObserver
Readiness *ReadinessObserver
JSON *marshaller.JSON
Version env.Version
}
// Register health for HTTP.
func Register(params RegisterParams) error {
mux := params.Mux
resister("/healthz", mux, params.Health.Observer, params.Version, params.JSON, true)
resister("/livez", mux, params.Liveness.Observer, params.Version, params.JSON, false)
resister("/readyz", mux, params.Readiness.Observer, params.Version, params.JSON, false)
return nil
}
func resister(path string, mux sh.ServeMux, ob *subscriber.Observer, version env.Version, json *marshaller.JSON, withErrors bool) {
mux.Handle("GET", path, func(resp http.ResponseWriter, _ *http.Request) {
resp.Header().Set("Content-Type", "application/json")
resp.Header().Set("Version", string(version))
var (
status int
response string
)
if err := ob.Error(); err != nil {
status = http.StatusServiceUnavailable
response = notServing
} else {
status = http.StatusOK
response = serving
}
resp.WriteHeader(status)
data := map[string]any{"status": response}
if withErrors {
errors := map[string]any{}
for n, e := range ob.Errors() {
if e == nil {
continue
}
errors[n] = e.Error()
}
if len(errors) > 0 {
data["errors"] = errors
}
}
b, _ := json.Marshal(data)
resp.Write(b)
})
}