pub trait Middleware: Send + Sync {
// Required method
fn process<'life0, 'async_trait>(
&'life0 self,
request: Request,
next: Arc<dyn Handler>,
) -> Pin<Box<dyn Future<Output = Result<Response>> + Send + 'async_trait>>
where Self: 'async_trait,
'life0: 'async_trait;
// Provided methods
fn should_continue(&self, _request: &Request) -> bool { ... }
fn di_registrations(&self) -> Vec<MiddlewareDiRegistration> ⓘ { ... }
}Expand description
Middleware trait for request/response processing.
Uses composition pattern instead of inheritance. Middleware can modify requests before passing to the next handler, or modify responses after the handler processes the request.
Required Methods§
Provided Methods§
Sourcefn should_continue(&self, _request: &Request) -> bool
fn should_continue(&self, _request: &Request) -> bool
Determines whether this middleware should be executed for the given request.
This method enables conditional execution of middleware, allowing the middleware chain to skip unnecessary middleware based on request properties.
§Performance Benefits
By implementing this method, middleware chains can achieve O(k) complexity instead of O(n), where k is the number of middleware that should run, and k <= n (total middleware count).
§Common Use Cases
- Skip authentication middleware for public endpoints
- Skip compression middleware for already compressed responses
- Skip CORS middleware for same-origin requests
- Skip rate limiting for internal/admin requests
§Default Implementation
By default, returns true (always execute), maintaining backward compatibility.
Sourcefn di_registrations(&self) -> Vec<MiddlewareDiRegistration> ⓘ
fn di_registrations(&self) -> Vec<MiddlewareDiRegistration> ⓘ
Returns DI singleton registrations contributed by this middleware.
Each entry is a (TypeId, Arc<dyn Any + Send + Sync>) pair representing
a singleton that the middleware owns and wants to expose to handlers
resolved via #[inject]. The default implementation returns an empty
vector, preserving backward compatibility for middleware that does not
own any DI-visible state.
Routers such as ServerRouter / UnifiedRouter call this method when
the middleware is registered via with_middleware() and merge the
resulting list into the server’s DI singleton scope. This lets a
middleware (for example SessionMiddleware) automatically register the
Arc<T> it constructs in its constructor, so callers no longer have to
thread a parallel with_di_registrations(...) call alongside every
with_middleware(...).
§Example
use std::any::TypeId;
use std::sync::Arc;
use reinhardt_http::{Middleware, MiddlewareDiRegistration};
struct MyStore;
struct MyMiddleware { store: Arc<MyStore> }
impl Middleware for MyMiddleware {
// ... process / should_continue ...
fn di_registrations(&self) -> Vec<MiddlewareDiRegistration> {
vec![(TypeId::of::<MyStore>(), Arc::clone(&self.store) as _)]
}
}Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".