-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_server.go
67 lines (57 loc) · 1.55 KB
/
http_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
package main
import (
"context"
"log/slog"
"net/http"
"os"
"time"
)
const (
patternGetNamespaces string = "GET /api/v1/namespaces"
)
type NamespaceListerServer struct {
*http.Server
}
func addInjectLoggerMiddleware(l *slog.Logger, next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := setLoggerIntoContext(r.Context(), l)
next.ServeHTTP(w, r.WithContext(ctx))
}
}
func addLogRequestMiddleware(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := getLoggerFromContext(r.Context())
l.Info("received request", "request", r.URL.Path)
next.ServeHTTP(w, r)
}
}
func NewServer(l *slog.Logger, lister NamespaceLister, userHeader string) *NamespaceListerServer {
// configure the server
h := http.NewServeMux()
h.Handle(patternGetNamespaces,
addInjectLoggerMiddleware(l,
addLogRequestMiddleware(
NewListNamespacesHandler(lister, userHeader))))
return &NamespaceListerServer{
Server: &http.Server{
Addr: getAddress(),
Handler: h,
ReadHeaderTimeout: 3 * time.Second,
},
}
}
func (s *NamespaceListerServer) Start(ctx context.Context) error {
// HTTP Server graceful shutdown
go func() {
<-ctx.Done()
sctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
//nolint:contextcheck
if err := s.Shutdown(sctx); err != nil {
getLoggerFromContext(ctx).Error("error gracefully shutting down the HTTP server", "error", err)
os.Exit(1)
}
}()
// start server
return s.ListenAndServe()
}