Function axum::extract::extractor_middleware[][src]

pub fn extractor_middleware<E>() -> ExtractorMiddlewareLayer<E>
Expand description

Convert an extractor into a middleware.

If the extractor succeeds the value will be discarded and the inner service will be called. If the extractor fails the rejection will be returned and the inner service will not be called.

This can be used to perform validation of requests if the validation doesn’t produce any useful output, and run the extractor for several handlers without repeating it in the function signature.

Note that if the extractor consumes the request body, as String or Bytes does, an empty body will be left in its place. Thus wont be accessible to subsequent extractors or handlers.

Example

use axum::{
    Router,
    async_trait,
    extract::{extractor_middleware, FromRequest, RequestParts},
    http::StatusCode,
    routing::{get, post},
};
use std::convert::Infallible;

struct MyExtractor;

#[async_trait]
impl<B> FromRequest<B> for MyExtractor
where
    B: Send,
{
    type Rejection = Infallible;

    async fn from_request(req: &mut RequestParts<B>) -> Result<Self, Self::Rejection> {
        // ...
    }
}

async fn handler() {}

async fn other_handler() {}

let app = Router::new()
    .route("/", get(handler))
    .route("/foo", post(other_handler))
    // The extractor will run before all routes
    .layer(extractor_middleware::<MyExtractor>());