-
Notifications
You must be signed in to change notification settings - Fork 71
/
checkgrp.go
88 lines (70 loc) · 2.27 KB
/
checkgrp.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
84
85
86
87
88
// Package checkgrp maintains the group of handlers for health checking.
package checkgrp
import (
"encoding/json"
"net/http"
"os"
"go.uber.org/zap"
)
// Handlers manages the set of check endpoints.
type Handlers struct {
Build string
Log *zap.SugaredLogger
}
// Readiness checks if the database is ready and if not will return a 500 status.
// Do not respond by just returning an error because further up in the call
// stack it will interpret that as a non-trusted error.
func (h Handlers) Readiness(w http.ResponseWriter, r *http.Request) {
status := "ok"
statusCode := http.StatusOK
// TODO: NOT SURE WHAT TO DO RIGHT NOW
data := struct {
Status string `json:"status"`
}{
Status: status,
}
if err := response(w, statusCode, data); err != nil {
h.Log.Errorw("readiness", "ERROR", err)
}
h.Log.Infow("readiness", "statusCode", statusCode, "method", r.Method, "path", r.URL.Path, "remoteaddr", r.RemoteAddr)
}
// Liveness returns simple status info if the service is alive. If the
// app is deployed to a Kubernetes cluster, it will also return pod, node, and
// namespace details via the Downward API. The Kubernetes environment variables
// need to be set within your Pod/Deployment manifest.
func (h Handlers) Liveness(w http.ResponseWriter, r *http.Request) {
host, err := os.Hostname()
if err != nil {
host = "unavailable"
}
data := struct {
Status string `json:"status,omitempty"`
Build string `json:"build,omitempty"`
Host string `json:"host,omitempty"`
}{
Status: "up",
Build: h.Build,
Host: host,
}
statusCode := http.StatusOK
if err := response(w, statusCode, data); err != nil {
h.Log.Errorw("liveness", "ERROR", err)
}
h.Log.Infow("liveness", "statusCode", statusCode, "method", r.Method, "path", r.URL.Path, "remoteaddr", r.RemoteAddr)
}
func response(w http.ResponseWriter, statusCode int, data any) error {
// Convert the response value to JSON.
jsonData, err := json.Marshal(data)
if err != nil {
return err
}
// Set the content type and headers once we know marshaling has succeeded.
w.Header().Set("Content-Type", "application/json")
// Write the status code to the response.
w.WriteHeader(statusCode)
// Send the result back to the client.
if _, err := w.Write(jsonData); err != nil {
return err
}
return nil
}