-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
52 lines (42 loc) · 1.1 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
package server
import (
"context"
"github.com/alexfalkowski/go-service/transport/meta"
"go.uber.org/fx"
"go.uber.org/zap"
)
// Server is a generic server.
type Server struct {
srv Serverer
sh fx.Shutdowner
logger *zap.Logger
svc string
}
// NewServer that can start and stop an underlying server.
func NewServer(svc string, srv Serverer, logger *zap.Logger, sh fx.Shutdowner) *Server {
return &Server{svc: svc, srv: srv, logger: logger, sh: sh}
}
// Start the server.
func (s *Server) Start() {
if !s.srv.IsEnabled() {
return
}
go s.start()
}
func (s *Server) start() {
addr := zap.Stringer("addr", s.srv)
s.logger.Info("starting server", addr, zap.String(meta.ServiceKey, s.svc))
if err := s.srv.Serve(); err != nil {
s.logger.Error("could not start server",
zap.String(meta.ServiceKey, s.svc), addr,
zap.Error(err), zap.NamedError("shutdown_error", s.sh.Shutdown()))
}
}
// Stop the server.
func (s *Server) Stop(ctx context.Context) {
if !s.srv.IsEnabled() {
return
}
s.logger.Info("stopping server",
zap.String(meta.ServiceKey, s.svc), zap.Error(s.srv.Shutdown(ctx)))
}