Skip to main content

Middleware

Trait Middleware 

Source
pub trait Middleware:
    Send
    + Sync
    + 'static {
    // Provided methods
    fn name(&self) -> &'static str { ... }
    fn order(&self) -> i32 { ... }
    fn before_request<'life0, 'async_trait>(
        &'life0 self,
        req: Request,
    ) -> Pin<Box<dyn Future<Output = Result<Request, Response>> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
    fn after_response<'life0, 'async_trait>(
        &'life0 self,
        res: Response,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'async_trait>>
       where Self: 'async_trait,
             'life0: 'async_trait { ... }
}
Expand description

A typed request/response middleware. Implement either hook (or both); the defaults pass through untouched.

use umbral::prelude::*;
use axum::extract::Request;
use axum::response::Response;

struct RequestId;

#[umbral::async_trait]
impl Middleware for RequestId {
    async fn before_request(&self, mut req: Request) -> Result<Request, Response> {
        req.headers_mut().insert("x-request-id", new_id().parse().unwrap());
        Ok(req)
    }
}

Provided Methods§

Source

fn name(&self) -> &'static str

A short label for diagnostics. Defaults to the type name.

Source

fn order(&self) -> i32

Declarative position in the chain. Lower values are OUTER — the middleware’s before_request runs earlier and its after_response runs later (onion order). Middleware with equal order keep their registration order (app-level before plugin-level; plugins in dependency order). MiddlewareStack::apply stable-sorts by this before installing, so a middleware can place itself relative to others (e.g. a session loader at -100, an auth gate at -50) without depending on registration timing. Default 0.

Source

fn before_request<'life0, 'async_trait>( &'life0 self, req: Request, ) -> Pin<Box<dyn Future<Output = Result<Request, Response>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Inspect or modify the request before it reaches the handler.

Return Ok(req) to continue (with the possibly-modified request), or Err(response) to short-circuit: the handler and all later middleware are skipped, and the response unwinds back out through the after_response hooks of the middleware that already ran.

Default: pass the request through unchanged.

Source

fn after_response<'life0, 'async_trait>( &'life0 self, res: Response, ) -> Pin<Box<dyn Future<Output = Response> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Inspect or modify the response on the way out.

Default: pass the response through unchanged.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§