/
checkgrp.go
88 lines (76 loc) · 2.47 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 (
"context"
"net/http"
"os"
"runtime"
"time"
"github.com/shohinsan/SaleSphereAPI/business/data/sqldb"
"github.com/shohinsan/SaleSphereAPI/foundation/logger"
"github.com/shohinsan/SaleSphereAPI/foundation/web"
"github.com/jmoiron/sqlx"
)
type handlers struct {
build string
log *logger.Logger
db *sqlx.DB
}
func new(build string, log *logger.Logger, db *sqlx.DB) *handlers {
return &handlers{
build: build,
db: db,
log: log,
}
}
// 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(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()
status := "ok"
statusCode := http.StatusOK
if err := sqldb.StatusCheck(ctx, h.db); err != nil {
status = "db not ready"
statusCode = http.StatusInternalServerError
h.log.Info(ctx, "readiness failure", "status", status)
}
data := struct {
Status string `json:"status"`
}{
Status: status,
}
return web.Respond(ctx, w, data, statusCode)
}
// 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(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
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"`
Name string `json:"name,omitempty"`
PodIP string `json:"podIP,omitempty"`
Node string `json:"node,omitempty"`
Namespace string `json:"namespace,omitempty"`
GOMAXPROCS int `json:"GOMAXPROCS,omitempty"`
}{
Status: "up",
Build: h.build,
Host: host,
Name: os.Getenv("KUBERNETES_NAME"),
PodIP: os.Getenv("KUBERNETES_POD_IP"),
Node: os.Getenv("KUBERNETES_NODE_NAME"),
Namespace: os.Getenv("KUBERNETES_NAMESPACE"),
GOMAXPROCS: runtime.GOMAXPROCS(0),
}
// This handler provides a free timer loop.
return web.Respond(ctx, w, data, http.StatusOK)
}