http.ServeMux with enhanced support for middleware, route grouping, and domain organization.
HTTPServer
TheHTTPServer type from httpserver/httpserver.go:18 is a service that runs an HTTP server with graceful shutdown:
Creating an HTTP Server
Fromhttpserver/httpserver.go:25:
The shutdown timeout controls how long the server waits for in-flight requests to complete during graceful shutdown.
Registering with Application
HTTP servers implement theRunner interface and can be registered as services:
./myapp run and shuts down gracefully on interrupt signals.
Route Registration
Handle() - Register Handlers
Use theHandle() method from httpserver/handlergroup.go:31 with Go 1.22+ routing syntax:
HandleFunc() - Register Functions
Fromhttpserver/handlergroup.go:36, for simple function handlers:
Path Parameters
Extract path parameters using Go’s standard library:HandlerGroup
TheHandlerGroup type from httpserver/handlergroup.go:8 organizes routes that share common middleware:
Creating Handler Groups
Fromhttpserver/handlergroup.go:14:
Mounting Handler Groups
UseHandleGroup() from httpserver/handlergroup.go:41 to mount groups at a path prefix:
Complete Example
Fromdemo-app/cmd/api/main.go:13, showing server setup with groups:
GET /ping- Top-level endpoint with trace ID middlewareGET /long- Top-level endpoint (tests graceful shutdown)GET /subApi/clock- Group endpoint with both trace ID and logging middleware
Mounting Domain APIs
Domains expose their HTTP API via aHandlerGroup:
This pattern keeps domain routing logic inside the domain while giving you flexibility in how you expose it.
Middleware Application
Server-Level Middleware
Applies to all routes on the server:Group-Level Middleware
Applies only to routes in the group fromhttpserver/handlergroup.go:19:
UseFunc() - Inline Middleware
Fromhttpserver/handlergroup.go:24, add middleware as a function:
Middleware Ordering
Middleware is applied in reverse order fromhttpserver/middleware.go:26:
Route Organization Patterns
Pattern 1: Versioned APIs
Pattern 2: Public vs Protected
Pattern 3: Domain-Based
Graceful Shutdown
Fromhttpserver/httpserver.go:30, the server handles shutdown automatically:
In-flight requests have
shutdownTimeout duration to complete before the server force-closes connections.Health Checks
TheHTTPServer implements Healthchecker from httpserver/httpserver.go:62:
Advanced Routing
Wildcard Paths
Method-Specific Routing
Multiple Path Params
Next Steps
Middleware
Learn how to create and apply HTTP middleware
Domains
Organize routes by business domain
Application Lifecycle
Register and run HTTP servers