Documentation
¶
Overview ¶
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.
Index ¶
- func ApplyMiddleware(arg MiddlewareArgs, next http.Handler, middleware ...MiddlewareFn) http.Handler
- func LoggerMiddlewareFn(args MiddlewareArgs, next http.Handler) http.Handler
- func RequestInjectHandler(logger *slog.Logger, traceIDHeaderName string, redactFn RedactFn, ...) http.Handler
- type Binder
- type DefaultRoute
- type GetPublicIPFunc
- type HTTPServer
- type Index
- type IndexHandlerFunc
- type MiddlewareArgs
- type MiddlewareFn
- type Option
- func WithEnableAllDefaultRoutes() Option
- func WithEnableDefaultRoutes(ids ...DefaultRoute) Option
- func WithIPHandlerFunc(handler http.HandlerFunc) Option
- func WithIndexHandlerFunc(handler IndexHandlerFunc) Option
- func WithLogger(logger *slog.Logger) Option
- func WithMethodNotAllowedHandlerFunc(handler http.HandlerFunc) Option
- func WithMetricsHandlerFunc(handler http.HandlerFunc) Option
- func WithMiddlewareFn(fn ...MiddlewareFn) Option
- func WithNotFoundHandlerFunc(handler http.HandlerFunc) Option
- func WithPProfHandlerFunc(handler http.HandlerFunc) Option
- func WithPanicHandlerFunc(handler http.HandlerFunc) Option
- func WithPingHandlerFunc(handler http.HandlerFunc) Option
- func WithRedactFn(fn RedactFn) Option
- func WithRequestTimeout(timeout time.Duration) Option
- func WithRouter(r *httprouter.Router) Option
- func WithServerAddr(addr string) Option
- func WithServerReadHeaderTimeout(timeout time.Duration) Option
- func WithServerReadTimeout(timeout time.Duration) Option
- func WithServerWriteTimeout(timeout time.Duration) Option
- func WithShutdownSignalChan(ch chan struct{}) Option
- func WithShutdownTimeout(timeout time.Duration) Option
- func WithShutdownWaitGroup(wg *sync.WaitGroup) Option
- func WithStatusHandlerFunc(handler http.HandlerFunc) Option
- func WithTLSCertData(pemCert, pemKey []byte) Option
- func WithTraceIDHeaderName(name string) Option
- func WithoutDefaultRouteLogger(routes ...DefaultRoute) Option
- func WithoutRouteLogger() Option
- type RedactFn
- type Route
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ApplyMiddleware ¶
func ApplyMiddleware(arg MiddlewareArgs, next http.Handler, middleware ...MiddlewareFn) http.Handler
ApplyMiddleware returns an http Handler with all middleware handler functions applied.
func LoggerMiddlewareFn ¶
func LoggerMiddlewareFn(args MiddlewareArgs, next http.Handler) http.Handler
LoggerMiddlewareFn returns the middleware handler function to handle logs.
Types ¶
type DefaultRoute ¶
type DefaultRoute string
DefaultRoute is the type for the default route names.
const ( // IndexRoute is the identifier to enable the index handler. IndexRoute DefaultRoute = "index" // IPRoute is the identifier to enable the ip handler. IPRoute DefaultRoute = "ip" // MetricsRoute is the identifier to enable the metrics handler. MetricsRoute DefaultRoute = "metrics" // PingRoute is the identifier to enable the ping handler. PingRoute DefaultRoute = "ping" // PprofRoute is the identifier to enable the pprof handler. PprofRoute DefaultRoute = "pprof" // StatusRoute is the identifier to enable the status handler. StatusRoute DefaultRoute = "status" )
type GetPublicIPFunc ¶
GetPublicIPFunc resolves the service public IP address.
func GetPublicIPDefaultFunc ¶
func GetPublicIPDefaultFunc() GetPublicIPFunc
GetPublicIPDefaultFunc returns the GetPublicIP function for a default ipify client.
type HTTPServer ¶
type HTTPServer struct {
// contains filtered or unexported fields
}
HTTPServer defines the HTTP Server object.
func New ¶
New constructs HTTP server with router, middleware, default operational routes, TLS, and graceful shutdown orchestration.
func (*HTTPServer) Shutdown ¶
func (h *HTTPServer) Shutdown(ctx context.Context) error
Shutdown gracefully shuts down server with timeout enforcement; wraps net/http Server.Shutdown().
func (*HTTPServer) StartServer ¶
func (h *HTTPServer) StartServer()
StartServer starts server in background using context from New().
func (*HTTPServer) StartServerCtx ¶
func (h *HTTPServer) StartServerCtx(ctx context.Context)
StartServerCtx starts server in background goroutine with context-aware shutdown support.
type Index ¶
type Index struct {
// Routes is the list of routes attached to the current service.
Routes []Route `json:"routes"`
}
Index contains the list of routes attached to the current service.
type IndexHandlerFunc ¶
type IndexHandlerFunc func([]Route) http.HandlerFunc
IndexHandlerFunc builds an index handler from the registered route list.
type MiddlewareArgs ¶
type MiddlewareArgs struct {
// Method is the HTTP method (e.g.: GET, POST, PUT, DELETE, ...).
Method string
// Path is the URL path.
Path string
// Description is the description of the route or a general description for the handler.
Description string
// TraceIDHeaderName is the Trace ID header name.
TraceIDHeaderName string
// RedactFunc is the function used to redact HTTP request and response dumps in the logs.
RedactFunc RedactFn
// Logger is the logger.
Logger *slog.Logger
// Rnd is the random generator.
Rnd *random.Rnd
}
MiddlewareArgs contains extra optional arguments to be passed to the middleware handler function MiddlewareFn.
type MiddlewareFn ¶
type MiddlewareFn func(args MiddlewareArgs, next http.Handler) http.Handler
MiddlewareFn is a function that wraps an http.Handler.
type Option ¶
type Option func(*config) error
Option configures an HTTPServer instance.
func WithEnableAllDefaultRoutes ¶
func WithEnableAllDefaultRoutes() Option
WithEnableAllDefaultRoutes enables all default routes on the server.
func WithEnableDefaultRoutes ¶
func WithEnableDefaultRoutes(ids ...DefaultRoute) Option
WithEnableDefaultRoutes sets the default routes to be enabled on the server.
func WithIPHandlerFunc ¶
func WithIPHandlerFunc(handler http.HandlerFunc) Option
WithIPHandlerFunc replaces the default ip handler function.
func WithIndexHandlerFunc ¶
func WithIndexHandlerFunc(handler IndexHandlerFunc) Option
WithIndexHandlerFunc replaces the index handler.
func WithLogger ¶ added in v1.111.1
WithLogger overrides the default logger.
func WithMethodNotAllowedHandlerFunc ¶
func WithMethodNotAllowedHandlerFunc(handler http.HandlerFunc) Option
WithMethodNotAllowedHandlerFunc http handler called when a request cannot be routed.
func WithMetricsHandlerFunc ¶
func WithMetricsHandlerFunc(handler http.HandlerFunc) Option
WithMetricsHandlerFunc replaces the default metrics handler function.
func WithMiddlewareFn ¶
func WithMiddlewareFn(fn ...MiddlewareFn) Option
WithMiddlewareFn adds one or more middleware handler functions to all routes (endpoints). These middleware handlers are applied in the provided order after the default ones and before the custom route ones.
func WithNotFoundHandlerFunc ¶
func WithNotFoundHandlerFunc(handler http.HandlerFunc) Option
WithNotFoundHandlerFunc http handler called when no matching route is found.
func WithPProfHandlerFunc ¶
func WithPProfHandlerFunc(handler http.HandlerFunc) Option
WithPProfHandlerFunc replaces the default pprof handler function.
func WithPanicHandlerFunc ¶
func WithPanicHandlerFunc(handler http.HandlerFunc) Option
WithPanicHandlerFunc http handler to handle panics recovered from http handlers.
func WithPingHandlerFunc ¶
func WithPingHandlerFunc(handler http.HandlerFunc) Option
WithPingHandlerFunc replaces the default ping handler function.
func WithRedactFn ¶
WithRedactFn set the function used to redact HTTP request and response dumps in the logs.
func WithRequestTimeout ¶
WithRequestTimeout sets a time limit for all routes after which a request receives a 503 Service Unavailable. Alternatively a custom timeout handler like http.TimeoutHandler can be added via WithMiddlewareFn().
func WithRouter ¶
func WithRouter(r *httprouter.Router) Option
WithRouter replaces the default router used by the httpServer (mostly used for test purposes with a mock router).
func WithServerAddr ¶
WithServerAddr sets the address the httpServer will bind to.
func WithServerReadHeaderTimeout ¶
WithServerReadHeaderTimeout sets the read header timeout.
func WithServerReadTimeout ¶
WithServerReadTimeout sets the read timeout.
func WithServerWriteTimeout ¶
WithServerWriteTimeout sets the write timeout.
func WithShutdownSignalChan ¶
func WithShutdownSignalChan(ch chan struct{}) Option
WithShutdownSignalChan sets the shared channel uset to signal a shutdown. When the channel signal is received the server will initiate the shutdown process.
func WithShutdownTimeout ¶
WithShutdownTimeout sets the shutdown timeout.
func WithShutdownWaitGroup ¶
WithShutdownWaitGroup sets the shared waiting group to communicate externally when the server is shutdown.
func WithStatusHandlerFunc ¶
func WithStatusHandlerFunc(handler http.HandlerFunc) Option
WithStatusHandlerFunc replaces the default status handler function.
func WithTLSCertData ¶
WithTLSCertData enable TLS with the given certificate and key data.
func WithTraceIDHeaderName ¶
WithTraceIDHeaderName overrides the default trace id header name.
func WithoutDefaultRouteLogger ¶
func WithoutDefaultRouteLogger(routes ...DefaultRoute) Option
WithoutDefaultRouteLogger disables the logger handler for the specified default routes.
func WithoutRouteLogger ¶
func WithoutRouteLogger() Option
WithoutRouteLogger disables the logger handler for all routes.
type Route ¶
type Route struct {
// Method is the HTTP method (e.g.: GET, POST, PUT, DELETE, ...).
Method string `json:"method"`
// Path is the URL path.
Path string `json:"path"`
// Description is the description of this route that is displayed by the /index endpoint.
Description string `json:"description"`
// Handler is the handler function.
Handler http.HandlerFunc `json:"-"`
// Middleware is a set of middleware to apply to this route.
Middleware []MiddlewareFn `json:"-"`
// DisableLogger disable the default logger when set to true.
DisableLogger bool `json:"-"`
// Timeout time limit after which a request receives a 503 Service Unavailable.
// If set, overrides the common value set with WithRequestTimeout.
Timeout time.Duration `json:"-"`
}
Route contains the HTTP route description.