-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
130 lines (103 loc) · 2.5 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package debug
import (
"context"
"errors"
"net"
"net/http"
"github.com/alexfalkowski/go-service/security"
"github.com/alexfalkowski/go-service/time"
tm "github.com/alexfalkowski/go-service/transport/meta"
"go.uber.org/fx"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
// ErrInvalidPort for HTTP.
var ErrInvalidPort = errors.New("invalid port")
// ServerParams for HTTP.
type ServerParams struct {
fx.In
Shutdowner fx.Shutdowner
Config *Config
Logger *zap.Logger
}
// Server for HTTP.
type Server struct {
Mux *http.ServeMux
server *http.Server
sh fx.Shutdowner
config *Config
logger *zap.Logger
list net.Listener
}
// NewServer for HTTP.
func NewServer(params ServerParams) (*Server, error) {
l, err := listener(params.Config)
if err != nil {
return nil, err
}
mux := http.NewServeMux()
s := &http.Server{
Handler: mux,
ReadTimeout: time.Timeout,
WriteTimeout: time.Timeout,
IdleTimeout: time.Timeout,
ReadHeaderTimeout: time.Timeout,
}
server := &Server{
Mux: mux,
server: s,
sh: params.Shutdowner,
config: params.Config,
logger: params.Logger,
list: l,
}
return server, nil
}
// Start the server.
func (s *Server) Start() error {
if s.list == nil {
return nil
}
go s.start()
return nil
}
// Stop the server.
func (s *Server) Stop(ctx context.Context) error {
if s.list == nil {
return nil
}
message := "stopping server"
err := s.server.Shutdown(ctx)
if err != nil {
s.logger.Error(message, zap.Error(err), zap.String(tm.ServiceKey, "debug"))
} else {
s.logger.Info(message, zap.String(tm.ServiceKey, "debug"))
}
return err
}
func (s *Server) start() {
s.logger.Info("starting server", zap.Stringer("addr", s.list.Addr()), zap.String(tm.ServiceKey, "debug"))
if err := s.serve(s.list); err != nil && !errors.Is(err, http.ErrServerClosed) {
fields := []zapcore.Field{zap.Stringer("addr", s.list.Addr()), zap.Error(err), zap.String(tm.ServiceKey, "debug")}
if err := s.sh.Shutdown(); err != nil {
fields = append(fields, zap.NamedError("shutdown_error", err))
}
s.logger.Error("could not start server", fields...)
}
}
func (s *Server) serve(l net.Listener) error {
se := s.config.Security
if security.IsEnabled(se) {
return s.server.ServeTLS(l, se.CertFile, se.KeyFile)
}
return s.server.Serve(l)
}
func listener(cfg *Config) (net.Listener, error) {
if !IsEnabled(cfg) {
return nil, nil
}
if cfg.Port == "" {
return nil, ErrInvalidPort
}
return net.Listen("tcp", ":"+cfg.Port)
}