-
Notifications
You must be signed in to change notification settings - Fork 0
/
health.go
102 lines (90 loc) · 2.52 KB
/
health.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package hyper
import (
"context"
"fmt"
"net/http"
"sync/atomic"
"github.com/infiniteloopcloud/log"
)
// isReady defines whether the api is ready for request
var isReady *atomic.Value
func init() {
isReady = &atomic.Value{}
}
// Ready enables the server to accept connections
func Ready() {
isReady.Store(true)
}
// NotReady disables the server to accept connections
func NotReady() {
isReady.Store(false)
}
// Livez returns http.StatusOk when the service does not need to be killed
func Livez(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
// Readyz returns http.StatusOk when the service is ready accept connections, otherwise Http.StatusServiceUnavailable
func Readyz(w http.ResponseWriter, r *http.Request) {
if !isReady.Load().(bool) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
func ReadyzWithChecks(checks ...func(ctx context.Context) error) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if !isReady.Load().(bool) {
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
for _, check := range checks {
if err := check(r.Context()); err != nil {
log.Error(r.Context(), err, "check in readyz")
http.Error(w, http.StatusText(http.StatusServiceUnavailable), http.StatusServiceUnavailable)
return
}
}
w.WriteHeader(http.StatusOK)
}
}
// Hello returns http.StatusOk and the Hello response
func Hello(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-type", "application/json")
w.WriteHeader(http.StatusOK)
//nolint:errcheck
w.Write([]byte(`{"msg":"Hello"}`))
}
func ServiceLive(ctx context.Context, url string) error {
resp, err := Request(ctx, nil, RequestOpts{
BaseURL: url,
Method: http.MethodGet,
Endpoint: "/livez",
Client: Client(),
})
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
err := fmt.Errorf("invalid status code %d", resp.StatusCode)
log.Error(ctx, err, "service not alive error")
return err
}
return nil
}
func ServiceReady(ctx context.Context, url string) error {
resp, err := Request(ctx, nil, RequestOpts{
BaseURL: url,
Method: http.MethodGet,
Endpoint: "/readyz",
Client: Client(),
})
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
err := fmt.Errorf("invalid status code %d", resp.StatusCode)
log.Error(ctx, err, "service readiness error")
return err
}
return nil
}