-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
69 lines (60 loc) · 1.51 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 main
import (
"context"
"errors"
"net/http"
"go.uber.org/fx"
"go.uber.org/zap"
)
type serveMuxIn struct {
fx.In
KeyHandler KeyHandler
KeySetHandler KeySetHandler
IssueHandler IssueHandler
SwaggerUIHandler SwaggerUIHandler
SwaggerYAMLHandler SwaggerYAMLHandler
}
func provideServer() fx.Option {
return fx.Options(
fx.Provide(
func(in serveMuxIn) (mux *http.ServeMux) {
mux = http.NewServeMux()
mux.Handle("/keys/"+in.KeyHandler.key.KeyID(), in.KeyHandler)
mux.Handle("/keys", in.KeySetHandler)
mux.Handle("/issue", in.IssueHandler)
mux.Handle("/swaggerui/", in.SwaggerUIHandler)
mux.Handle("/openapi.yaml", in.SwaggerYAMLHandler)
return
},
func(l *zap.Logger, cfg Configuration, mux *http.ServeMux) *http.Server {
return &http.Server{
Addr: cfg.Address,
Handler: mux,
}
},
),
fx.Invoke(
func(l fx.Lifecycle, s fx.Shutdowner, logger *zap.Logger, server *http.Server) {
l.Append(fx.Hook{
OnStart: func(context.Context) error {
go func() {
defer func() {
if err := s.Shutdown(); err != nil {
logger.Error("error shutting down server", zap.Error(err))
}
}()
err := server.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Error("error starting server", zap.Error(err))
}
}()
return nil
},
OnStop: func(ctx context.Context) error {
return server.Shutdown(ctx)
},
})
},
),
)
}