Crate reqwest_conditional_middleware

Source
Expand description

The only export of this crate is a struct ConditionalMiddleware for creating conditional middlewares. This struct implements the Middleware trait and forwards requests on to the middleware that it wraps.

The conditional wrapper holds a closure that will be run for each request. If the closure returns true, then the inner middleware will run. Otherwise it will be skipped and the current request will be passed along to the next middleware.

§Example

Short-circuits a middleware stack and returns OK whenever the request method is GET

use reqwest::{Request, Response};
use reqwest_conditional_middleware::ConditionalMiddleware;
use reqwest_middleware::{Middleware, Next, Result};
use http::Extensions;

struct AlwaysOk;

#[async_trait::async_trait]
impl Middleware for AlwaysOk {
    async fn handle(
        &self,
        _req: Request,
        _extensions: &mut Extensions,
        _next: Next<'_>,
    ) -> Result<Response> {
        let builder = http::Response::builder().status(http::StatusCode::OK);
        Ok(builder.body("").unwrap().into())
    }
}

let conditional = ConditionalMiddleware::new(
    AlwaysOk,
    |req: &Request| req.method() == http::Method::GET
);

Structs§