-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhttpserver.go
More file actions
283 lines (221 loc) · 7.21 KB
/
httpserver.go
File metadata and controls
283 lines (221 loc) · 7.21 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
Package httpserver defines a default configurable HTTP server with common routes
and options.
Optional common routes are defined in the routes.go file. The routes include:
- /ip: Returns the public IP address of the service instance.
- /metrics: Returns Prometheus metrics (default and custom).
- /ping: Pings the service to check if it is alive.
- /pprof: Returns pprof profiling data for the selected profile.
- /status: Checks and returns the health status of the service, including
external services or components.
For a usage example, refer to the examples/service/internal/cli/bind.go file.
*/
package httpserver
import (
"context"
"crypto/tls"
"fmt"
"net"
"net/http"
"github.com/Vonage/gosrvlib/pkg/httputil"
"github.com/Vonage/gosrvlib/pkg/logging"
"go.uber.org/zap"
)
// Binder is an interface to allow configuring the HTTP router.
type Binder interface {
// BindHTTP returns the routes.
BindHTTP(ctx context.Context) []Route
}
// NopBinder returns a simple no-operation binder.
func NopBinder() Binder {
return &nopBinder{}
}
type nopBinder struct{}
func (b *nopBinder) BindHTTP(_ context.Context) []Route { return nil }
// HTTPServer defines the HTTP Server object.
type HTTPServer struct {
cfg *config
ctx context.Context //nolint:containedctx
httpServer *http.Server
listener net.Listener
logger *zap.Logger
}
// Start configures and start a new HTTP server.
//
// Deprecated: Use New() and StartServerCtx() instead.
func Start(ctx context.Context, binder Binder, opts ...Option) error {
h, err := New(ctx, binder, opts...)
if err != nil {
return err
}
h.StartServer()
return nil
}
// New configures new HTTP server.
func New(ctx context.Context, binder Binder, opts ...Option) (*HTTPServer, error) {
cfg := defaultConfig()
for _, applyOpt := range opts {
err := applyOpt(cfg)
if err != nil {
return nil, err
}
}
logger := logging.WithComponent(ctx, "httpserver").With(
zap.String("addr", cfg.serverAddr),
)
cfg.setRouter(ctx)
loadRoutes(ctx, logger, binder, cfg)
listener, err := netListener(ctx, cfg.serverAddr, cfg.tlsConfig)
if err != nil {
return nil, err
}
return &HTTPServer{
cfg: cfg,
ctx: ctx,
httpServer: &http.Server{
Addr: cfg.serverAddr,
Handler: cfg.router,
ReadHeaderTimeout: cfg.serverReadHeaderTimeout,
ReadTimeout: cfg.serverReadTimeout,
TLSConfig: cfg.tlsConfig,
WriteTimeout: cfg.serverWriteTimeout,
},
listener: listener,
logger: logger,
},
nil
}
// StartServerCtx starts the current server and return without blocking.
// This ignore the context passed to the New() method.
func (h *HTTPServer) StartServerCtx(ctx context.Context) {
// wait for shutdown signal or context cancelation
go func() {
select {
case <-h.cfg.shutdownSignalChan:
h.logger.Debug("shutdown notification received")
case <-ctx.Done():
h.logger.Warn("context canceled")
}
// The shutdown context is independent from the parent context.
shutdownCtx, cancel := context.WithTimeout(context.Background(), h.cfg.shutdownTimeout)
defer cancel()
_ = h.Shutdown(shutdownCtx) //nolint:contextcheck
}()
// start server
go func() {
h.serve()
}()
h.cfg.shutdownWaitGroup.Add(1)
h.logger.Info("listening for http requests")
}
// StartServer starts the current server and return without blocking.
func (h *HTTPServer) StartServer() {
h.StartServerCtx(h.ctx)
}
// Shutdown gracefully shuts down the server without interrupting any active connections.
// Wraps the standard net/http/Server_Shutdown method.
func (h *HTTPServer) Shutdown(ctx context.Context) error {
h.logger.Debug("shutting down http server")
err := h.httpServer.Shutdown(ctx)
h.cfg.shutdownWaitGroup.Add(-1)
h.logger.Debug("http server shutdown complete", zap.Error(err))
return err //nolint:wrapcheck
}
func (h *HTTPServer) serve() {
err := h.httpServer.Serve(h.listener)
if err == http.ErrServerClosed {
h.logger.Debug("closed http server")
return
}
h.logger.Error("unexpected http server failure", zap.Error(err))
}
func netListener(ctx context.Context, serverAddr string, tlsConfig *tls.Config) (net.Listener, error) {
var (
ls net.Listener
err error
)
if tlsConfig == nil {
var lc net.ListenConfig
ls, err = lc.Listen(ctx, "tcp", serverAddr)
} else {
ls, err = tls.Listen("tcp", serverAddr, tlsConfig)
}
if err != nil {
return nil, fmt.Errorf("failed creating the http server address listener: %w", err)
}
return ls, nil
}
func loadRoutes(ctx context.Context, l *zap.Logger, binder Binder, cfg *config) {
l.Debug("loading default routes")
routes := newDefaultRoutes(cfg)
l.Debug("loading service routes")
customRoutes := binder.BindHTTP(ctx)
routes = append(routes, customRoutes...)
l.Debug("applying routes")
for _, r := range routes {
l.Debug("binding route", zap.String("path", r.Path))
// Add default and custom middleware functions
middleware := cfg.commonMiddleware(r.DisableLogger, r.Timeout)
middleware = append(middleware, r.Middleware...)
args := MiddlewareArgs{
Method: r.Method,
Path: r.Path,
Description: r.Description,
TraceIDHeaderName: cfg.traceIDHeaderName,
RedactFunc: cfg.redactFn,
Logger: l,
}
handler := ApplyMiddleware(args, r.Handler, middleware...)
cfg.router.Handler(r.Method, r.Path, handler)
}
// attach route index if enabled
if cfg.isIndexRouteEnabled() {
l.Debug("enabling route index handler")
_, disableLogger := cfg.disableDefaultRouteLogger[IndexRoute]
middleware := cfg.commonMiddleware(disableLogger, 0)
args := MiddlewareArgs{
Method: http.MethodGet,
Path: indexPath,
Description: "Index",
TraceIDHeaderName: cfg.traceIDHeaderName,
RedactFunc: cfg.redactFn,
Logger: l,
}
handler := ApplyMiddleware(args, cfg.indexHandlerFunc(routes), middleware...)
cfg.router.Handler(args.Method, args.Path, handler)
}
}
func defaultIndexHandler(routes []Route) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
data := &Index{Routes: routes}
httputil.SendJSON(r.Context(), w, http.StatusOK, data)
}
}
func defaultIPHandler(fn GetPublicIPFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
status := http.StatusOK
ip, err := fn(r.Context())
if err != nil {
status = http.StatusFailedDependency
}
httputil.SendText(r.Context(), w, status, ip)
}
}
func defaultPingHandler(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusOK)
}
func defaultStatusHandler(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusOK)
}
func notImplementedHandler(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusNotImplemented)
}
func defaultNotFoundHandlerFunc(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusNotFound)
}
func defaultMethodNotAllowedHandlerFunc(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusMethodNotAllowed)
}
func defaultPanicHandlerFunc(w http.ResponseWriter, r *http.Request) {
httputil.SendStatus(r.Context(), w, http.StatusInternalServerError)
}