main gradient

docs

middleware

Middleware

Middleware in Rapid is done almost identical to the way actix-web approaches it except for file-based routing. Read more about how to compose middleware via traits in actix-web here. In Rapid, all you need to do is define a file inside your routes directory called _middleware with a public top-level struct named Middleware. Below is an entire example of a middleware function that prints "Hello World!" to the console before every request:

use std::future::{ready, Ready};

use actix_web::{
    dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
    Error,
};
use futures_util::future::LocalBoxFuture;

// This must be called "Middleware" so that the Rapid compiler can detect it
pub struct Middleware;

impl<S, B> Transform<S, ServiceRequest> for Middleware
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = HelloWorldMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(HelloWorldMiddleware { service }))
    }
}

pub struct HelloWorldMiddleware<S> {
    service: S,
}

impl<S, B> Service<ServiceRequest> for HelloWorldMiddleware<S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        println!("Hello World!");

        let fut = self.service.call(req);

        Box::pin(async move {
            let res = fut.await?;
            Ok(res)
        })
    }
}
_middleware.rs