pub struct MiddlewareStack { /* private fields */ }Expand description
A stack of middleware that wraps a handler.
The stack executes middleware in order:
beforehooks run first-to-last (registration order)- Handler executes (if no middleware short-circuited)
afterhooks run last-to-first (reverse order)
§Example
ⓘ
let mut stack = MiddlewareStack::new();
stack.push(LoggingMiddleware);
stack.push(AuthMiddleware);
stack.push(CorsMiddleware);
let response = stack.execute(&handler, &ctx, &mut request).await;Implementations§
Source§impl MiddlewareStack
impl MiddlewareStack
Sourcepub fn with_capacity(capacity: usize) -> Self
pub fn with_capacity(capacity: usize) -> Self
Creates a middleware stack with pre-allocated capacity.
Sourcepub fn push<M: Middleware + 'static>(&mut self, middleware: M)
pub fn push<M: Middleware + 'static>(&mut self, middleware: M)
Adds middleware to the end of the stack.
Middleware added first will have its before run first and after run last.
Sourcepub fn push_arc(&mut self, middleware: Arc<dyn Middleware>)
pub fn push_arc(&mut self, middleware: Arc<dyn Middleware>)
Adds middleware wrapped in an Arc.
Useful for sharing middleware across multiple stacks.
Sourcepub async fn execute<H: Handler>(
&self,
handler: &H,
ctx: &RequestContext,
req: &mut Request,
) -> Response
pub async fn execute<H: Handler>( &self, handler: &H, ctx: &RequestContext, req: &mut Request, ) -> Response
Executes the middleware stack with the given handler.
§Execution Order
- Each middleware’s
beforehook runs in order - If any
beforereturnsBreak, skip remaining middleware and handler - Handler executes
- Each middleware’s
afterhook runs in reverse order
§Short-Circuit Behavior
If middleware N calls Break(response):
- Middleware N+1..end
beforehooks do NOT run - Handler does NOT run
- Middleware 0..N
afterhooks STILL run (in reverse: N, N-1, …, 0)
This ensures cleanup middleware (like timing or logging) always runs.
Trait Implementations§
Source§impl Default for MiddlewareStack
impl Default for MiddlewareStack
Source§fn default() -> MiddlewareStack
fn default() -> MiddlewareStack
Returns the “default value” for a type. Read more
Auto Trait Implementations§
impl Freeze for MiddlewareStack
impl !RefUnwindSafe for MiddlewareStack
impl Send for MiddlewareStack
impl Sync for MiddlewareStack
impl Unpin for MiddlewareStack
impl !UnwindSafe for MiddlewareStack
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, _span: NoopSpan) -> Self
fn instrument(self, _span: NoopSpan) -> Self
Instruments this future with a span (no-op when disabled).
Source§fn in_current_span(self) -> Self
fn in_current_span(self) -> Self
Instruments this future with the current span (no-op when disabled).