-
Notifications
You must be signed in to change notification settings - Fork 3
/
mux.go
55 lines (44 loc) · 1.04 KB
/
mux.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
package debug
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/alexfalkowski/go-service/time"
"go.uber.org/fx"
"go.uber.org/zap"
)
func mux(lc fx.Lifecycle, cfg *Config, logger *zap.Logger) *http.ServeMux {
mux := http.NewServeMux()
server := &http.Server{
Addr: fmt.Sprintf("localhost:%s", cfg.Port),
Handler: mux,
ReadHeaderTimeout: time.Timeout,
}
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
go start(logger, server)
return nil
},
OnStop: func(ctx context.Context) error {
stop(ctx, logger, server)
return nil
},
})
return mux
}
func start(l *zap.Logger, s *http.Server) {
l.Info("starting debug server")
if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
l.Error("could not start debug server", zap.Error(err))
}
}
func stop(ctx context.Context, l *zap.Logger, s *http.Server) {
message := "stopping debug server"
err := s.Shutdown(ctx)
if err != nil {
l.Error(message, zap.Error(err))
} else {
l.Info(message)
}
}