httpserver

package
v1.130.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 22 Imported by: 0

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

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.

func RequestInjectHandler

func RequestInjectHandler(
	logger *slog.Logger,
	traceIDHeaderName string,
	redactFn RedactFn,
	rnd *random.Rnd,
	next http.Handler,
) http.Handler

RequestInjectHandler wraps all incoming requests and injects a logger in the request scoped context.

Types

type Binder

type Binder interface {
	// BindHTTP returns the routes.
	BindHTTP(ctx context.Context) []Route
}

Binder is an interface to allow configuring the HTTP router.

func NopBinder

func NopBinder() Binder

NopBinder returns no-operation binder that supplies no custom routes to router.

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

type GetPublicIPFunc func(context.Context) (string, error)

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

func New(ctx context.Context, binder Binder, opts ...Option) (*HTTPServer, error)

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

func WithLogger(logger *slog.Logger) Option

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

func WithRedactFn(fn RedactFn) Option

WithRedactFn set the function used to redact HTTP request and response dumps in the logs.

func WithRequestTimeout

func WithRequestTimeout(timeout time.Duration) Option

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

func WithServerAddr(addr string) Option

WithServerAddr sets the address the httpServer will bind to.

func WithServerReadHeaderTimeout

func WithServerReadHeaderTimeout(timeout time.Duration) Option

WithServerReadHeaderTimeout sets the read header timeout.

func WithServerReadTimeout

func WithServerReadTimeout(timeout time.Duration) Option

WithServerReadTimeout sets the read timeout.

func WithServerWriteTimeout

func WithServerWriteTimeout(timeout time.Duration) Option

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

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout sets the shutdown timeout.

func WithShutdownWaitGroup

func WithShutdownWaitGroup(wg *sync.WaitGroup) Option

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

func WithTLSCertData(pemCert, pemKey []byte) Option

WithTLSCertData enable TLS with the given certificate and key data.

func WithTraceIDHeaderName

func WithTraceIDHeaderName(name string) Option

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 RedactFn

type RedactFn func(s string) string

RedactFn redacts sensitive values from logged text payloads.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL