Function actix_web_lab::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_lab::middleware::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_lab::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:
use actix_web_lab::middleware::Next;
async fn my_extracting_mw(
string_body: String,
query: web::Query<HashMap<String, String>>,
req: ServiceRequest,
next: Next<impl MessageBody>,
) -> Result<ServiceResponse<impl MessageBody>, Error> {
// pre-processing
next.call(req).await
// post-processing
}