pub trait Middleware: Send + Sync {
// Provided methods
fn before<'a>(
&'a self,
_ctx: &'a RequestContext,
_req: &'a mut Request,
) -> BoxFuture<'a, ControlFlow> { ... }
fn after<'a>(
&'a self,
_ctx: &'a RequestContext,
_req: &'a Request,
response: Response,
) -> BoxFuture<'a, Response> { ... }
fn name(&self) -> &'static str { ... }
}Expand description
The core middleware trait.
Middleware wraps request handling with pre-processing and post-processing hooks.
Implementations must be thread-safe (Send + Sync) as middleware may be shared
across concurrent requests.
§Implementation Guide
before: Inspect/modify the request, optionally short-circuitafter: Inspect/modify the response
Both methods have default implementations that do nothing, so you can implement only what you need.
§Cancel-Safety
Middleware should check ctx.checkpoint() for long operations to support
graceful cancellation when clients disconnect or timeouts occur.
§Example: Request Timing
ⓘ
use std::time::Instant;
use fastapi_core::middleware::{Middleware, ControlFlow};
struct TimingMiddleware;
impl Middleware for TimingMiddleware {
async fn before(&self, ctx: &RequestContext, req: &mut Request) -> ControlFlow {
// Store start time in request extensions (future feature)
ControlFlow::Continue
}
async fn after(&self, _ctx: &RequestContext, _req: &Request, mut resp: Response) -> Response {
// Add timing header
resp = resp.header("X-Response-Time", b"42ms".to_vec());
resp
}
}Provided Methods§
Sourcefn before<'a>(
&'a self,
_ctx: &'a RequestContext,
_req: &'a mut Request,
) -> BoxFuture<'a, ControlFlow>
fn before<'a>( &'a self, _ctx: &'a RequestContext, _req: &'a mut Request, ) -> BoxFuture<'a, ControlFlow>
Called before the handler executes.
§Parameters
ctx: Request context with cancellation supportreq: Mutable request that can be inspected or modified
§Returns
ControlFlow::Continueto proceed to the next middleware/handlerControlFlow::Break(response)to short-circuit and return immediately
§Default Implementation
Returns ControlFlow::Continue (no-op).
Sourcefn after<'a>(
&'a self,
_ctx: &'a RequestContext,
_req: &'a Request,
response: Response,
) -> BoxFuture<'a, Response>
fn after<'a>( &'a self, _ctx: &'a RequestContext, _req: &'a Request, response: Response, ) -> BoxFuture<'a, Response>
Called after the handler executes.
§Parameters
ctx: Request context with cancellation supportreq: The request (read-only at this point)response: The response from the handler or previousafterhooks
§Returns
The response to pass to the next after hook or to return to the client.
§Default Implementation
Returns the response unchanged (no-op).