/
server.go
160 lines (132 loc) · 3.62 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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
package server
import (
"context"
"net/http"
"os/signal"
"reflect"
"strconv"
"syscall"
"time"
"go.uber.org/zap"
)
// Service is a http.Handler with Startup and Shutdown lifecycle
type Service interface {
http.Handler
// Startup controls app startup
Startup(ctx context.Context) error
// Shutdown controls app shutdown
Shutdown(ctx context.Context) error
}
// Metrics represents metrics Startup and Shutdown lifecycle and Handle middleware
type Metrics interface {
// Handle HTTP middleware metrics handler
Handle(next http.Handler) http.Handler
// Startup controls metrics startup
Startup(ctx context.Context) error
// Shutdown controls metrics shutdown
Shutdown(ctx context.Context) error
}
// Server wraps the Service with additional http and app lifecycle handling
type Server struct {
http.Server
App Service
Address string
Port int
CertFile string
KeyFile string
PathPrefix string
StartupTimeout time.Duration
ShutdownTimeout time.Duration
Logger *zap.Logger
Debug bool
Metrics Metrics
}
// New create new Server
func New(app Service, options ...Option) *Server {
s := &Server{}
s.App = app
s.Port = 8000
s.MaxHeaderBytes = 1 << 20
s.StartupTimeout = time.Second * 10
s.ShutdownTimeout = time.Second * 10
s.Logger = zap.NewNop()
// build up middleware handlers in reverse order
// Handler: application
s.Handler = s.App
// handle no-op routes /healthcheck, /favicon.ico
s.Handler = noopHandler(s.Handler)
for _, option := range options {
option(s)
}
// Handler: prefixes
if s.PathPrefix != "" {
s.Handler = http.StripPrefix(s.PathPrefix, s.Handler)
}
// Handler: recover from panics
s.Handler = s.panicHandler(s.Handler)
// Handler: observe metrics if enabled
if !isNil(s.Metrics) {
s.Handler = s.Metrics.Handle(s.Handler)
}
if s.Addr == "" {
s.Addr = s.Address + ":" + strconv.Itoa(s.Port)
}
s.ErrorLog = newServerErrorLog(s.Logger)
return s
}
// Run server that terminates on SIGINT, SIGTERM signals
func (s *Server) Run() {
ctx, cancel := signal.NotifyContext(
context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
s.RunContext(ctx)
}
// RunContext run server with context
func (s *Server) RunContext(ctx context.Context) {
s.startup(ctx)
go func() {
if err := s.listenAndServe(); err != nil && err != http.ErrServerClosed {
s.Logger.Fatal("listen", zap.Error(err))
}
}()
s.Logger.Info("listen", zap.String("addr", s.Addr))
if !isNil(s.Metrics) {
if err := s.Metrics.Startup(ctx); err != nil {
s.Logger.Fatal("metrics-startup", zap.Error(err))
}
}
<-ctx.Done()
s.shutdown(context.Background())
}
func isNil(c any) bool {
return c == nil || (reflect.ValueOf(c).Kind() == reflect.Ptr && reflect.ValueOf(c).IsNil())
}
func (s *Server) startup(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, s.StartupTimeout)
defer cancel()
if err := s.App.Startup(ctx); err != nil {
s.Logger.Fatal("app-startup", zap.Error(err))
}
}
func (s *Server) shutdown(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, s.ShutdownTimeout)
defer cancel()
s.Logger.Info("shutdown")
if !isNil(s.Metrics) {
if err := s.Metrics.Shutdown(ctx); err != nil {
s.Logger.Error("metrics-shutdown", zap.Error(err))
}
}
if err := s.Shutdown(ctx); err != nil {
s.Logger.Error("server-shutdown", zap.Error(err))
}
if err := s.App.Shutdown(ctx); err != nil {
s.Logger.Error("app-shutdown", zap.Error(err))
}
}
func (s *Server) listenAndServe() error {
if s.CertFile != "" && s.KeyFile != "" {
return s.ListenAndServeTLS(s.CertFile, s.KeyFile)
}
return s.ListenAndServe()
}