-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
58 lines (45 loc) · 1.27 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
package http
import (
"encoding/json"
"net/http"
"github.com/alexfalkowski/go-health/subscriber"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
const (
serving = "SERVING"
notServing = "NOT_SERVING"
)
// Register health for HTTP.
func Register(server *http.Server, hob *HealthObserver, lob *LivenessObserver, rob *ReadinessObserver) error {
if err := resister("/health", server, hob.Observer); err != nil {
return err
}
if err := resister("/liveness", server, lob.Observer); err != nil {
return err
}
if err := resister("/readiness", server, hob.Observer); err != nil {
return err
}
return nil
}
// nolint:forcetypeassert
func resister(path string, server *http.Server, ob *subscriber.Observer) error {
mux := server.Handler.(*runtime.ServeMux)
return mux.HandlePath("GET", path, func(w http.ResponseWriter, r *http.Request, pathParams map[string]string) {
var (
status int
response string
)
if err := ob.Error(); err != nil {
status = http.StatusServiceUnavailable
response = notServing
} else {
status = http.StatusOK
response = serving
}
w.WriteHeader(status)
w.Header().Set("Content-Type", "application/json")
data := map[string]string{"status": response}
json.NewEncoder(w).Encode(data) // nolint:errcheck
})
}