Skip to main content

MiddlewareLayer

Trait MiddlewareLayer 

Source
pub trait MiddlewareLayer:
    Send
    + Sync
    + 'static {
    // Required methods
    fn call(
        &self,
        req: Request,
        next: Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> + Sync + Send>,
    ) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>>;
    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: Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>> + Sync + Send>, ) -> Pin<Box<dyn Future<Output = Response<Body>> + Send>>

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

Implementors§