Documentation
¶
Overview ¶
Package httprouter provides an HTTP request router with built-in cross-origin request forgery (CSRF) protection, middleware support, and OpenAPI spec generation. Routes are registered under a common path prefix and may optionally pass through a middleware chain before reaching the handler.
Index ¶
- type HTTPMiddlewareFunc
- type Router
- func (r *Router) AddMiddleware(fn HTTPMiddlewareFunc)
- func (r *Router) Origin() string
- func (r *Router) Prefix() string
- func (r *Router) RegisterCatchAll(path string, middleware bool) error
- func (r *Router) RegisterFS(path string, fs fs.FS, middleware bool, spec *openapi.PathItem) error
- func (r *Router) RegisterOpenAPI(path string, middleware bool) error
- func (r *Router) RegisterPath(path string, params *jsonschema.Schema, pathitem httprequest.PathItem) error
- func (r *Router) RegisterSecurityScheme(name string, scheme SecurityScheme) error
- func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
- func (r *Router) Spec() *openapi.Spec
- type SecurityScheme
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type HTTPMiddlewareFunc ¶
type HTTPMiddlewareFunc func(http.HandlerFunc) http.HandlerFunc
HTTPMiddlewareFunc is a function that wraps an http.HandlerFunc, returning a new handler that may run logic before and/or after calling the next handler.
func Cors ¶ added in v1.6.17
func Cors(origin string, headers ...string) HTTPMiddlewareFunc
Cors returns an HTTPMiddlewareFunc that sets CORS response headers on every request. The origin parameter controls the Access-Control-Allow-Origin header:
- Empty string or "*": allow all origins (header value is set to "*")
- Any other value: used verbatim as the allowed origin
headers lists the request headers that clients are permitted to send. If none are provided the header value defaults to "*". For preflight OPTIONS requests the middleware writes a 204 No Content response and does not call the next handler.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router is an HTTP request multiplexer that wraps http.ServeMux with cross-origin protection, an optional middleware chain and an openapi.Spec that is populated as routes are registered.
func NewRouter ¶
func NewRouter(ctx context.Context, mux *http.ServeMux, prefix, origin, title, version string, middleware ...HTTPMiddlewareFunc) (*Router, error)
NewRouter creates a new router with the given prefix, origin, title, version and middleware. The prefix is normalised to a path. The origin controls cross-origin request handling:
- Empty string: same-origin requests only (CSRF enabled, no CORS)
- "*": allow all cross-origin requests (CORS enabled, CSRF bypassed)
- A specific origin in the form "scheme://host[:port]" (CORS and CSRF enabled, with the origin added as a trusted CSRF origin)
The title and version are used to create the OpenAPI spec for the router.
func (*Router) AddMiddleware ¶
func (r *Router) AddMiddleware(fn HTTPMiddlewareFunc)
AddMiddleware appends fn to the router's middleware chain. Middleware is applied in order: the first added becomes the outermost wrapper and executes first when a request arrives. This method must be called before any routes are registered, because routes capture the chain at registration time.
func (*Router) Origin ¶
Origin returns the trusted origin configured for cross-origin protection. It returns an empty string when only same-origin requests are allowed, "*" when all origins are trusted, or a specific "scheme://host[:port]" value.
func (*Router) Prefix ¶ added in v1.6.19
Prefix returns the normalised path prefix that all relative routes are registered under.
func (*Router) RegisterCatchAll ¶ added in v1.6.14
RegisterCatchAll registers a structured-404 handler at the literal "/" path in the underlying ServeMux. Because http.ServeMux treats "/" as a catch-all that matches any request not handled by a more-specific pattern, this ensures unmatched requests return a JSON 404 instead of Go's plain-text response.
func (*Router) RegisterFS ¶
RegisterFS registers a file server at path that serves static assets from the given fs.FS. If path is relative (does not start with "/") the router prefix is prepended; if path is absolute it is used as-is. The combined prefix is stripped from incoming requests before the file lookup. A trailing slash is ensured so that http.ServeMux treats it as a subtree pattern, matching all sub-paths.
When spec is non-nil the corresponding openapi.PathItem is added to the router's OpenAPI specification under the resolved path. When middleware is true the handler is wrapped by the router's middleware chain.
func (*Router) RegisterOpenAPI ¶
RegisterOpenAPI registers a handler at path that serves the router's openapi.Spec as JSON on GET requests and returns 405 Method Not Allowed for all other HTTP methods. If path is relative the router prefix is prepended; if path is absolute it is used as-is. When middleware is true the handler is wrapped by the router's middleware chain.
func (*Router) RegisterPath ¶ added in v1.6.19
func (r *Router) RegisterPath(path string, params *jsonschema.Schema, pathitem httprequest.PathItem) error
RegisterPath registers a [PathItem] handler at path. If path is relative the router prefix is prepended. Any security schemes referenced by the path item's OpenAPI operations must already be registered on the router; matching handlers are wrapped with those security schemes before the router's middleware chain is applied.
func (*Router) RegisterSecurityScheme ¶ added in v1.6.21
func (r *Router) RegisterSecurityScheme(name string, scheme SecurityScheme) error
RegisterSecurityScheme registers a security scheme with the router. The scheme can then be referenced in the OpenAPI spec by name.
func (*Router) ServeHTTP ¶
func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)
ServeHTTP dispatches the request to the matching registered handler after applying cross-origin protection. It implements the http.Handler interface.
type SecurityScheme ¶ added in v1.6.21
type SecurityScheme interface {
// Wrap returns a HTTP handler function that wraps the security scheme around
// the provided handler, enforcing the required scopes.
Wrap(handler http.HandlerFunc, scopes []string) http.HandlerFunc
// Spec returns the openapi.PathItem for a path with optional path parameters
Spec() openapi.SecurityScheme
}