-
Notifications
You must be signed in to change notification settings - Fork 3
/
http.go
63 lines (51 loc) · 1.42 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
package http
import (
"encoding/json"
"net/http"
"github.com/alexfalkowski/go-health/subscriber"
"github.com/alexfalkowski/go-service/config"
shttp "github.com/alexfalkowski/go-service/transport/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
)
const (
serving = "SERVING"
notServing = "NOT_SERVING"
)
// Register health for HTTP.
func Register(server *shttp.Server, hob *HealthObserver, lob *LivenessObserver, rob *ReadinessObserver) error {
resister("/health", server.Mux, hob.Observer, true)
resister("/liveness", server.Mux, lob.Observer, false)
resister("/readiness", server.Mux, hob.Observer, false)
return nil
}
func resister(path string, mux *runtime.ServeMux, ob *subscriber.Observer, withErrors bool) {
mux.HandlePath("GET", path, func(w http.ResponseWriter, r *http.Request, p 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 := config.Map{"status": response}
if withErrors {
errors := config.Map{}
for n, e := range ob.Errors() {
if e == nil {
continue
}
errors[n] = e.Error()
}
if len(errors) > 0 {
data["errors"] = errors
}
}
json.NewEncoder(w).Encode(data) // nolint:errcheck,errchkjson
})
}