Available on crate feature validate-request only.
Expand description

Middleware that validates requests.

Example

use tower_http::validate_request::ValidateRequestHeaderLayer;
use hyper::{Request, Response, Body, Error};
use http::{StatusCode, header::ACCEPT};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};

async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
    Ok(Response::new(Body::empty()))
}

let mut service = ServiceBuilder::new()
    // Require the `Accept` header to be `application/json`, `*/*` or `application/*`
    .layer(ValidateRequestHeaderLayer::accept("application/json"))
    .service_fn(handle);

// Requests with the correct value are allowed through
let request = Request::builder()
    .header(ACCEPT, "application/json")
    .body(Body::empty())
    .unwrap();

let response = service
    .ready()
    .await?
    .call(request)
    .await?;

assert_eq!(StatusCode::OK, response.status());

// Requests with an invalid value get a `406 Not Acceptable` response
let request = Request::builder()
    .header(ACCEPT, "text/strings")
    .body(Body::empty())
    .unwrap();

let response = service
    .ready()
    .await?
    .call(request)
    .await?;

assert_eq!(StatusCode::NOT_ACCEPTABLE, response.status());

Custom validation can be made by implementing ValidateRequest:

use tower_http::validate_request::{ValidateRequestHeaderLayer, ValidateRequest};
use hyper::{Request, Response, Body, Error};
use http::{StatusCode, header::ACCEPT};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};

#[derive(Clone, Copy)]
pub struct MyHeader { /* ...  */ }

impl<B> ValidateRequest<B> for MyHeader {
    type ResponseBody = Body;

    fn validate(
        &mut self,
        request: &mut Request<B>,
    ) -> Result<(), Response<Self::ResponseBody>> {
        // validate the request...
    }
}

async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
    Ok(Response::new(Body::empty()))
}


let service = ServiceBuilder::new()
    // Validate requests using `MyHeader`
    .layer(ValidateRequestHeaderLayer::custom(MyHeader { /* ... */ }))
    .service_fn(handle);

Or using a closure:

use tower_http::validate_request::{ValidateRequestHeaderLayer, ValidateRequest};
use hyper::{Request, Response, Body, Error};
use http::{StatusCode, header::ACCEPT};
use tower::{Service, ServiceExt, ServiceBuilder, service_fn};

async fn handle(request: Request<Body>) -> Result<Response<Body>, Error> {
    // ...
}

let service = ServiceBuilder::new()
    .layer(ValidateRequestHeaderLayer::custom(|request: &mut Request<Body>| {
        // Validate the request
    }))
    .service_fn(handle);

Structs

Traits