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