-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
76 lines (60 loc) · 1.84 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
package http
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// NewServer for HTTP.
func NewServer(lc fx.Lifecycle, s fx.Shutdowner, cfg *Config, logger *zap.Logger) *http.Server {
mux := runtime.NewServeMux(runtime.WithIncomingHeaderMatcher(customMatcher))
addr := fmt.Sprintf(":%s", cfg.Port)
server := &http.Server{Addr: addr, Handler: mux}
lc.Append(fx.Hook{
OnStart: func(context.Context) error {
listener, err := net.Listen("tcp", addr)
if err != nil {
return err
}
go startServer(s, server, listener, cfg, logger)
return nil
},
OnStop: func(ctx context.Context) error {
return stopServer(ctx, server, cfg, logger)
},
})
return server
}
func startServer(s fx.Shutdowner, server *http.Server, listener net.Listener, cfg *Config, logger *zap.Logger) {
logger.Info("starting http server", zap.String("port", cfg.Port))
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
fields := []zapcore.Field{zap.String("port", cfg.Port), zap.Error(err)}
if err := s.Shutdown(); err != nil {
fields = append(fields, zap.NamedError("shutdown_error", err))
}
logger.Error("could not start http server", fields...)
}
}
func stopServer(ctx context.Context, server *http.Server, cfg *Config, logger *zap.Logger) error {
logger.Info("stopping http server", zap.String("port", cfg.Port))
if err := server.Shutdown(ctx); err != nil {
logger.Error("could not stop http server", zap.String("port", cfg.Port), zap.Error(err))
return err
}
return nil
}
func customMatcher(key string) (string, bool) {
switch key {
case "Request-Id", "Authorization":
return key, true
case "User-Agent":
return "ua", true
default:
return runtime.DefaultHeaderMatcher(key)
}
}