/
server.go
189 lines (159 loc) · 4.93 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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package http
import (
"net/http"
"os"
"os/signal"
"time"
"context"
"github.com/ONSdigital/dp-net/v2/request"
"github.com/ONSdigital/log.go/v2/log"
"github.com/justinas/alice"
)
const (
RequestIDHandlerKey string = "RequestID"
LogHandlerKey string = "Log"
ResponseWriteGrace time.Duration = 100 * time.Millisecond
)
// Server is a http.Server with sensible defaults, which supports
// configurable middleware and timeouts, and shuts down cleanly
// on SIGINT/SIGTERM
type Server struct {
http.Server
middleware map[string]alice.Constructor
middlewareOrder []string
Alice *alice.Chain
CertFile string
KeyFile string
DefaultShutdownTimeout time.Duration
HandleOSSignals bool
RequestTimeout time.Duration
TimeoutMessage string
}
// NewServer creates a new server
func NewServer(bindAddr string, router http.Handler) *Server {
middleware := map[string]alice.Constructor{
RequestIDHandlerKey: request.HandlerRequestID(16),
LogHandlerKey: log.Middleware,
}
return &Server{
Alice: nil,
middleware: middleware,
middlewareOrder: []string{RequestIDHandlerKey, LogHandlerKey},
Server: http.Server{
Handler: router,
Addr: bindAddr,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
ReadHeaderTimeout: 0,
IdleTimeout: 0,
MaxHeaderBytes: 0,
},
HandleOSSignals: true,
DefaultShutdownTimeout: 10 * time.Second,
}
}
// NewServerWithTimeout creates a new server with request timeout duration
// and a message that will be in the response body
func NewServerWithTimeout(bindAddr string, router http.Handler, timeout time.Duration, timeoutMessage string) *Server {
server := NewServer(bindAddr, router)
server.RequestTimeout = timeout
server.TimeoutMessage = timeoutMessage
return server
}
func (s *Server) prep() {
var m []alice.Constructor
for _, v := range s.middlewareOrder {
if mw, ok := s.middleware[v]; ok {
m = append(m, mw)
continue
}
panic("middleware not found: " + v)
}
s.Server.Handler = alice.New(m...).Then(s.Handler)
}
// ListenAndServe sets up SIGINT/SIGTERM signals, builds the middleware
// chain, and creates/starts a http.Server instance
//
// If CertFile/KeyFile are both set, the http.Server instance is started
// using ListenAndServeTLS. Otherwise, ListenAndServe is used.
//
// Specifying one of CertFile/KeyFile without the other will panic.
func (s *Server) ListenAndServe() error {
if s.HandleOSSignals {
return s.listenAndServeHandleOSSignals()
}
return s.listenAndServe()
}
// ListenAndServeTLS sets KeyFile and CertFile, then calls ListenAndServe
func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
if len(certFile) == 0 || len(keyFile) == 0 {
panic("either CertFile/KeyFile must be blank, or both provided")
}
s.KeyFile = keyFile
s.CertFile = certFile
return s.ListenAndServe()
}
// Shutdown will gracefully shutdown the server, using a default shutdown
// timeout if a context is not provided.
func (s *Server) Shutdown(ctx context.Context) error {
if ctx == nil {
ctx, _ = context.WithTimeout(context.Background(), s.DefaultShutdownTimeout)
}
return doShutdown(ctx, &s.Server)
}
func (s *Server) listenAndServe() error {
s.prep()
if len(s.CertFile) > 0 || len(s.KeyFile) > 0 {
return doListenAndServeTLS(s, s.CertFile, s.KeyFile)
}
return doListenAndServe(s)
}
func (s *Server) listenAndServeHandleOSSignals() error {
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, os.Kill)
s.listenAndServeAsync()
<-stop
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
return s.Shutdown(ctx)
}
func (s *Server) listenAndServeAsync() {
s.prep()
if len(s.CertFile) > 0 || len(s.KeyFile) > 0 {
go func() {
if err := doListenAndServeTLS(s, s.CertFile, s.KeyFile); err != nil {
log.Error(context.Background(), "http server returned error", err)
os.Exit(1)
}
}()
} else {
go func() {
if err := doListenAndServe(s); err != nil {
log.Error(context.Background(), "http server returned error", err)
os.Exit(1)
}
}()
}
}
func timeoutHandler(s *Server) *http.Server {
if s.RequestTimeout > 0 {
// give some time for the response to be written
if s.WriteTimeout <= s.RequestTimeout {
s.WriteTimeout = s.RequestTimeout + ResponseWriteGrace
}
timeoutMsg := "connection timeout"
if s.TimeoutMessage != "" {
timeoutMsg = s.TimeoutMessage
}
s.Handler = http.TimeoutHandler(s.Handler, s.RequestTimeout, timeoutMsg)
}
return &s.Server
}
var doListenAndServe = func(httpServer *Server) error {
return timeoutHandler(httpServer).ListenAndServe()
}
var doListenAndServeTLS = func(httpServer *Server, certFile, keyFile string) error {
return timeoutHandler(httpServer).ListenAndServeTLS(certFile, keyFile)
}
var doShutdown = func(ctx context.Context, httpServer *http.Server) error {
return httpServer.Shutdown(ctx)
}