Skip to main content

MiddlewareLayer

Trait MiddlewareLayer 

Source
pub trait MiddlewareLayer:
    Send
    + Sync
    + 'static {
    // Required methods
    fn call(
        &self,
        req: Request,
        next: BoxedNext,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>>;
    fn clone_box(&self) -> Box<dyn MiddlewareLayer>;
}
Expand description

Trait for middleware that can be applied to RustAPI

This trait allows both Tower layers and custom middleware to be used with the .layer() method.

§Example: Implementing a custom simple logger middleware

use rustapi_core::middleware::{MiddlewareLayer, BoxedNext};
use rustapi_core::{Request, Response};
use std::pin::Pin;
use std::future::Future;

#[derive(Clone)]
struct SimpleLogger;

impl MiddlewareLayer for SimpleLogger {
    fn call(
        &self,
        req: Request,
        next: BoxedNext,
    ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>> {
        Box::pin(async move {
            println!("Incoming request: {} {}", req.method(), req.uri());
            let response = next(req).await;
            println!("Response status: {}", response.status());
            response
        })
    }

    fn clone_box(&self) -> Box<dyn MiddlewareLayer> {
        Box::new(self.clone())
    }
}

Required Methods§

Source

fn call( &self, req: Request, next: BoxedNext, ) -> Pin<Box<dyn Future<Output = Response> + Send + 'static>>

Apply this middleware to a request, calling next to continue the chain

Source

fn clone_box(&self) -> Box<dyn MiddlewareLayer>

Clone this middleware into a boxed trait object

Trait Implementations§

Source§

impl Clone for Box<dyn MiddlewareLayer>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Implementors§