Function actix_web::middleware::from_fn

source ·
pub fn from_fn<F, Es>(mw_fn: F) -> MiddlewareFn<F, Es>
Expand description

Wraps an async function to be used as a middleware.

§Examples

The wrapped function should have the following form:

use actix_web::middleware::{self, Next};

async fn my_mw(
    req: ServiceRequest,
    next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, Error> {
    // pre-processing
    next.call(req).await
    // post-processing
}

Then use in an app builder like this:

use actix_web::{
    App, Error,
    dev::{ServiceRequest, ServiceResponse, Service as _},
};
use actix_web::middleware::from_fn;

App::new()
    .wrap(from_fn(my_mw))

It is also possible to write a middleware that automatically uses extractors, similar to request handlers, by declaring them as the first parameters. As usual, take care with extractors that consume the body stream, since handlers will no longer be able to read it again without putting the body “back” into the request object within your middleware.

use actix_web::middleware::Next;

async fn my_extracting_mw(
    accept: Header<Accept>,
    query: Query<HashMap<String, String>>,
    req: ServiceRequest,
    next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, Error> {
    // pre-processing
    next.call(req).await
    // post-processing
}