-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhttpserver.go
More file actions
273 lines (213 loc) · 7.79 KB
/
httpserver.go
File metadata and controls
273 lines (213 loc) · 7.79 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
/*
Package httpserver provides a configurable, production-oriented HTTP server
bootstrap for Go services.
# Problem
Starting a robust HTTP service usually requires repetitive infrastructure code:
listener setup, route registration, middleware chaining, panic/404/405
handling, request timeouts, TLS wiring, graceful shutdown, and optional
observability endpoints. Implementing this independently in each service leads
to inconsistency and duplicated maintenance effort.
# Solution
This package defines a reusable server assembly with:
- option-driven configuration ([New] + functional [Option]s)
- pluggable route binding via [Binder]
- configurable default route set for operational endpoints
- shared middleware application model
- graceful shutdown orchestration via context and/or signal channel
Custom service routes are supplied by a [Binder], while default routes can be
enabled selectively (or all at once) through options.
# Default Operational Routes
When enabled, the built-in route set includes:
- /ip: returns the service public IP (via ipify integration)
- /metrics: returns metrics payload (501 by default unless replaced)
- /ping: lightweight liveness endpoint
- /pprof/*option: pprof profiling endpoints
- /status: service health endpoint
- / (index): generated route index
# Features
- Graceful lifecycle control: non-blocking start, context-aware shutdown,
configurable shutdown timeout, external wait-group and signal integration.
- Router defaults: standardized not-found, method-not-allowed, and panic
handlers with structured logging.
- Middleware pipeline: common middleware (logger/timeout) plus global and
per-route middleware composition.
- Observability integration: trace-id propagation hooks, HTTP data redaction,
and optional pprof/metrics/status routes.
- Transport flexibility: plain TCP or TLS listener creation from cert/key
material.
- Safe defaults with extensibility: overridable handlers and server
parameters for production customization.
# Benefits
httpserver reduces service bootstrap boilerplate, enforces consistent runtime
behavior across projects, and accelerates delivery of HTTP services with
operational best practices built in.
For a usage example, refer to examples/service/internal/cli/bind.go.
*/
package httpserver
import (
"context"
"crypto/tls"
"fmt"
"log/slog"
"net"
"net/http"
"github.com/tecnickcom/gogen/pkg/httputil"
)
// Binder is an interface to allow configuring the HTTP router.
type Binder interface {
// BindHTTP returns the routes.
BindHTTP(ctx context.Context) []Route
}
// NopBinder returns no-operation binder that supplies no custom routes to router.
func NopBinder() Binder {
return &nopBinder{}
}
// nopBinder is a no-operation binder implementation.
type nopBinder struct{}
// BindHTTP implements the Binder interface.
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
}
// New constructs HTTP server with router, middleware, default operational routes, TLS, and graceful shutdown orchestration.
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
}
}
cfg.logger = cfg.logger.With(
slog.String("component", "httpserver"),
slog.String("addr", cfg.serverAddr),
)
cfg.httpresp = httputil.NewHTTPResp(cfg.logger)
cfg.setRouter(ctx)
loadRoutes(ctx, 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,
},
nil
}
// StartServerCtx starts server in background goroutine with context-aware shutdown support.
func (h *HTTPServer) StartServerCtx(ctx context.Context) {
// wait for shutdown signal or context cancelation
go func() { //nolint:gosec
select {
case <-h.cfg.shutdownSignalChan:
h.cfg.logger.Debug("shutdown notification received")
case <-ctx.Done():
h.cfg.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.cfg.logger.Info("listening for http requests")
}
// StartServer starts server in background using context from New().
func (h *HTTPServer) StartServer() {
h.StartServerCtx(h.ctx)
}
// Shutdown gracefully shuts down server with timeout enforcement; wraps net/http Server.Shutdown().
func (h *HTTPServer) Shutdown(ctx context.Context) error {
h.cfg.logger.Debug("shutting down http server")
err := h.httpServer.Shutdown(ctx)
h.cfg.shutdownWaitGroup.Add(-1)
h.cfg.logger.With(slog.Any("error", err)).Debug("http server shutdown complete")
return err //nolint:wrapcheck
}
// serve starts serving HTTP requests.
func (h *HTTPServer) serve() {
err := h.httpServer.Serve(h.listener)
if err == http.ErrServerClosed {
h.cfg.logger.Debug("closed http server")
return
}
h.cfg.logger.With(slog.Any("error", err)).Error("unexpected http server failure")
}
// netListener creates a network listener for the given server address and TLS configuration.
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
}
// loadRoutes loads and binds the routes to the HTTP server router.
func loadRoutes(ctx context.Context, binder Binder, cfg *config) {
cfg.logger.Debug("loading default routes")
routes := newDefaultRoutes(cfg)
cfg.logger.Debug("loading service routes")
customRoutes := binder.BindHTTP(ctx)
routes = append(routes, customRoutes...)
cfg.logger.Debug("applying routes")
for _, r := range routes {
cfg.logger.With(slog.String("path", r.Path)).Debug("binding route")
// 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: cfg.logger,
Rnd: cfg.rnd,
}
handler := ApplyMiddleware(args, r.Handler, middleware...)
cfg.router.Handler(r.Method, r.Path, handler)
}
// attach route index if enabled
if cfg.isIndexRouteEnabled() {
cfg.logger.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: cfg.logger,
Rnd: cfg.rnd,
}
handler := ApplyMiddleware(args, cfg.indexHandlerFunc(routes), middleware...)
cfg.router.Handler(args.Method, args.Path, handler)
}
}