AnyMiddleware

Struct AnyMiddleware 

Source
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

§Performance Considerations

Using AnyMiddleware involves dynamic dispatch and heap allocation, which has a small performance overhead compared to using concrete types directly. However, this overhead is typically negligible in HTTP server contexts where network I/O dominates performance characteristics.

§Examples

§Storing Mixed Middleware Types

use http_kit::{Request, Response, Result, Middleware, Endpoint, middleware::AnyMiddleware};

struct LoggingMiddleware;
impl Middleware for LoggingMiddleware {
    async fn handle(&self, request: &mut Request, next: impl Endpoint) -> Result<Response> {
        println!("Request: {}", request.uri());
        next.respond(request).await
    }
}

struct TimingMiddleware;
impl Middleware for TimingMiddleware {
    async fn handle(&self, request: &mut Request, next: impl Endpoint) -> Result<Response> {
        let start = std::time::Instant::now();
        let response = next.respond(request).await;
        println!("Duration: {:?}", start.elapsed());
        response
    }
}

// Store different middleware types in a collection
let middleware_stack: Vec<AnyMiddleware> = vec![
    AnyMiddleware::new(LoggingMiddleware),
    AnyMiddleware::new(TimingMiddleware),
];

§Dynamic Middleware Configuration

use http_kit::{Request, Response, Result, Middleware, Endpoint, middleware::AnyMiddleware};

fn create_middleware(name: &str) -> Option<AnyMiddleware> {
    match name {
        "logging" => Some(AnyMiddleware::new(LoggingMiddleware)),
        "timing" => Some(AnyMiddleware::new(TimingMiddleware)),
        _ => None,
    }
}

Implementations§

Source§

impl AnyMiddleware

Source

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};

struct CustomMiddleware {
    prefix: String,
}

impl Middleware for CustomMiddleware {
    async fn handle(&self, request: &mut Request, next: impl Endpoint) -> Result<Response> {
        println!("{}: Processing {}", self.prefix, request.uri());
        next.respond(request).await
    }
}

let middleware = CustomMiddleware { prefix: "API".to_string() };
let any_middleware = AnyMiddleware::new(middleware);
Source

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};

struct MyMiddleware;
impl Middleware for MyMiddleware {
    async fn handle(&self, request: &mut Request, next: impl Endpoint) -> Result<Response> {
        next.respond(request).await
    }
}

let any_middleware = AnyMiddleware::new(MyMiddleware);
println!("Middleware type: {}", any_middleware.name());
// Output: Middleware type: my_crate::MyMiddleware

Trait Implementations§

Source§

impl Debug for AnyMiddleware

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Middleware for AnyMiddleware

Source§

async fn handle( &mut self, request: &mut Request, next: impl Endpoint, ) -> Result<Response>

Processes a request through the middleware chain. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.