-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
97 lines (79 loc) · 2.24 KB
/
server.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
package healthcheck
import (
"context"
"encoding/json"
"github.com/prometheus/client_golang/prometheus/promhttp"
"log/slog"
"net/http"
"os"
"strconv"
"time"
)
type Server struct {
opts serverOptions
}
func NewServer(hc IHealthcheck, opts ...func(*serverOptions)) (*Server, error) {
options := serverOptions{
port: 8000,
healthcheck: hc,
logger: slog.New(slog.NewJSONHandler(os.Stdout, nil)),
}
for _, opt := range opts {
opt(&options)
}
return &Server{opts: options}, nil
}
func (s *Server) Run(ctx context.Context) error {
mux := http.NewServeMux()
mux.HandleFunc("/live", s.handleLive)
mux.HandleFunc("/ready", ReadyHandler(s.opts.healthcheck))
mux.Handle("/metrics", promhttp.Handler())
httpServer := &http.Server{
Addr: ":" + strconv.Itoa(s.opts.port),
Handler: mux,
}
go func() {
<-ctx.Done()
ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) //nolint:gomnd
defer cancel()
if err := httpServer.Shutdown(ctx); err != nil {
s.opts.logger.ErrorContext(ctx, "shutdown webserver", slog.String("error", err.Error()))
}
}()
go func() {
if err := httpServer.ListenAndServe(); err != nil {
s.opts.logger.ErrorContext(ctx, "run status server", slog.String("error", err.Error()))
}
}()
return nil
}
func (s *Server) handleLive(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
}
// ReadyHandler build a http.HandlerFunc from healthcheck.
func ReadyHandler(healthcheck IHealthcheck) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
const unknownResp = `{"status":"unknown","checks":[]}`
ctx := req.Context()
w.Header().Set("Content-Type", "application/json")
report := healthcheck.RunAllChecks(ctx)
reportJson, err := json.Marshal(report)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(unknownResp))
return
}
switch report.Status {
default:
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(unknownResp))
case StatusUp:
w.WriteHeader(http.StatusOK)
_, _ = w.Write(reportJson)
case StatusDown:
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write(reportJson)
}
}
}