pub struct AnyMiddleware(/* private fields */);Expand description
Type-erased middleware that can hold any middleware implementation behind a trait object.
AnyMiddleware provides dynamic dispatch for middleware, allowing you to store
different middleware types in the same collection or pass them around without
knowing their concrete types at compile time. This is particularly useful for:
- Building flexible middleware chains with different middleware types
- Plugin systems where middleware is loaded dynamically
- Configuration-driven middleware stacks
- Storing middleware in collections or registries
Implementations§
Source§impl AnyMiddleware
impl AnyMiddleware
Sourcepub fn new(middleware: impl Middleware + 'static) -> Self
pub fn new(middleware: impl Middleware + 'static) -> Self
Creates a new type-erased middleware wrapper around the given middleware implementation.
This method takes any type that implements Middleware and wraps it in an
AnyMiddleware that can be stored alongside other middleware of different types.
The original middleware type information is erased, but the functionality is preserved.
§Arguments
middleware- Any middleware implementation
§Examples
use http_kit::{Request, Response, Result, Middleware, Endpoint, middleware::AnyMiddleware, Body, BoxHttpError};
use http_kit::middleware::MiddlewareError;
struct CustomMiddleware {
prefix: String,
}
impl Middleware for CustomMiddleware {
type Error = BoxHttpError;
async fn handle<E: Endpoint>(&mut self, request: &mut Request, mut next: E) -> Result<Response, MiddlewareError<E::Error, Self::Error>> {
println!("{}: Processing {}", self.prefix, request.uri());
next.respond(request).await.map_err(MiddlewareError::Endpoint)
}
}
let middleware = CustomMiddleware { prefix: "API".to_string() };
let any_middleware = AnyMiddleware::new(middleware);Sourcepub fn name(&self) -> &'static str
pub fn name(&self) -> &'static str
Returns the type name of the underlying middleware implementation.
This method provides introspection capabilities for debugging, logging, or monitoring purposes. The returned string is the fully qualified type name of the original middleware type.
§Examples
use http_kit::{Request, Response, Result, Middleware, Endpoint, middleware::AnyMiddleware, Body, BoxHttpError};
use http_kit::middleware::MiddlewareError;
struct MyMiddleware;
impl Middleware for MyMiddleware {
type Error = BoxHttpError;
async fn handle<E: Endpoint>(&mut self, request: &mut Request, mut next: E) -> Result<Response, MiddlewareError<E::Error, Self::Error>> {
next.respond(request).await.map_err(MiddlewareError::Endpoint)
}
}
let any_middleware = AnyMiddleware::new(MyMiddleware);
println!("Middleware type: {}", any_middleware.name());
// Output: Middleware type: my_crate::MyMiddleware