httpserver package provides an HTTP server with middleware support, handler groups, and graceful shutdown capabilities.
HTTPServer Type
TheHTTPServer type represents an HTTP server with middleware support and graceful shutdown.
Constructor
*HTTPServer
Creates a new HTTPServer instance.Parameters:
port(string): The port number to listen on (e.g., “8080”)shutdownTimeout(time.Duration): Maximum time to wait for graceful shutdown
HTTPServer Methods
Run
error
Starts the HTTP server and handles graceful shutdown when the context is canceled.The server will:
- Start listening on the configured port
- Block until the context is canceled (e.g., interrupt signal)
- Gracefully shut down within the shutdown timeout
Healthcheck
any
Returns health check information for the HTTP server.
HandlerGroup Type
TheHandlerGroup represents a group of HTTP handlers that share common middleware.
Constructor
*HandlerGroup
Creates a new HandlerGroup with an initialized http.ServeMux.
HandlerGroup Methods
Handle
void
Registers an http.Handler for the given pattern.
HandleFunc
void
Registers an http.HandlerFunc for the given pattern.
HandleGroup
void
Applies
http.StripPrefix to the handler and registers it for the given pattern. Useful for mounting sub-routers.Use
void
Adds one or more middlewares to the HandlerGroup’s middleware chain.
UseFunc
void
Adds functions as middleware to the HandlerGroup’s middleware chain.
ServeHTTP
void
Implements the http.Handler interface, allowing HandlerGroup to be used as an HTTP handler itself.
Middleware Interface
The Middleware interface defines HTTP middleware.func(http.Handler) http.Handler
Wraps an http.Handler with middleware logic.
MiddlewareFunc
A convenience type that implements the Middleware interface.Built-in Middleware
RecoverMiddleware
TheRecoverMiddleware catches panics in HTTP handlers and returns an HTTP 500 response.
*RecoverMiddleware
Creates a new RecoverMiddleware instance.
- Catch any panic in downstream handlers
- Log the panic with request context
- Return HTTP 500 Internal Server Error response
- Prevent the server from crashing
FileServer Type
TheFileServer serves static files from an embedded file system.
*FileServer
Creates a new FileServer for serving static files.Parameters:
fs(fs.FS): The file system to serve (can be embedded)basePath(string): The URL path prefix (e.g., “/static”)port(string): The port to listen on