-
Notifications
You must be signed in to change notification settings - Fork 0
/
healthz.go
95 lines (79 loc) Β· 1.59 KB
/
healthz.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
package healthz
import (
"log"
"net/http"
)
func NewHealthz(opts ...Option) *healthz {
defaults := &options{
mux: http.NewServeMux(),
addr: "0.0.0.0:80",
endpoint: "/healthz",
response: nil,
logger: log.Default(),
}
for _, opt := range opts {
opt(defaults)
}
defaults.mux.Handle(defaults.endpoint, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write(defaults.response)
if err != nil {
defaults.logger.Printf("response write error: %w", err)
}
}))
return &healthz{
mux: defaults.mux,
addr: defaults.addr,
endpoint: defaults.endpoint,
response: defaults.response,
logger: defaults.logger,
}
}
func (h *healthz) Mux() *http.ServeMux {
return h.mux
}
func (h *healthz) Serve() error {
return http.ListenAndServe(h.addr, h.mux)
}
func (h *healthz) MustServe() {
err := http.ListenAndServe(h.addr, h.mux)
if err != nil {
panic(err)
}
}
type Option func(*options)
func Mux(mux *http.ServeMux) Option {
return func(o *options) {
o.mux = mux
}
}
func Addr(addr string) Option {
return func(o *options) {
o.addr = addr
}
}
func Endpoint(endpoint string) Option {
return func(o *options) {
o.endpoint = endpoint
}
}
func Response(response []byte) Option {
return func(o *options) {
o.response = response
}
}
func Logger(logger Printer) Option {
return func(o *options) {
o.logger = logger
}
}
type Printer interface {
Printf(format string, v ...interface{})
}
type healthz options
type options struct {
mux *http.ServeMux
addr string
endpoint string
response []byte
logger Printer
}