forked from trussworks/go-sample-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhealth_check.go
68 lines (57 loc) · 1.52 KB
/
health_check.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
package handlers
import (
"encoding/json"
"net/http"
"github.com/spf13/viper"
"bin/bork/pkg/apperrors"
)
// NewHealthCheckHandler is a constructor for HealthCheckHandler
func NewHealthCheckHandler(base HandlerBase, config *viper.Viper) HealthCheckHandler {
return HealthCheckHandler{
HandlerBase: HandlerBase{},
Config: config,
}
}
// HealthCheckHandler returns the API status
type HealthCheckHandler struct {
Config *viper.Viper
HandlerBase
}
type status string
const (
statusPass status = "pass"
)
type healthCheck struct {
Status status `json:"status"`
Datetime string `json:"datetime"`
Version string `json:"version"`
Timestamp string `json:"timestamp"`
}
// Handle handles a web request and returns a health check JSON payload
func (h HealthCheckHandler) Handle() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
statusReport := healthCheck{
Status: statusPass,
Version: h.Config.GetString("APPLICATION_VERSION"),
Datetime: h.Config.GetString("APPLICATION_DATETIME"),
Timestamp: h.Config.GetString("APPLICATION_TS"),
}
js, err := json.Marshal(statusReport)
if err != nil {
h.WriteErrorResponse(r.Context(), w, err)
return
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(js)
if err != nil {
h.WriteErrorResponse(r.Context(), w, err)
return
}
default:
h.WriteErrorResponse(r.Context(), w, &apperrors.MethodNotAllowedError{Method: r.Method})
return
}
}
}