pub struct Extension<T>(pub T);
Expand description

A middleware that inserts the value into the Extensions during the call.

This is a good way to inject extensions to middleware deeper in the stack

use reqwest::{Client, Request, Response};
use reqwest_middleware::{ClientBuilder, Middleware, Next, Result, Extension};
use task_local_extensions::Extensions;

#[derive(Clone)]
struct LogName(&'static str);
struct LoggingMiddleware;

#[async_trait::async_trait]
impl Middleware for LoggingMiddleware {
    async fn handle(
        &self,
        req: Request,
        extensions: &mut Extensions,
        next: Next<'_>,
    ) -> Result<Response> {
        // get the log name or default to "unknown"
        let name = extensions
            .get()
            .map(|&LogName(name)| name)
            .unwrap_or("unknown");
        println!("[{name}] Request started {req:?}");
        let res = next.run(req, extensions).await;
        println!("[{name}] Result: {res:?}");
        res
    }
}

async fn run() {
    let reqwest_client = Client::builder().build().unwrap();
    let client = ClientBuilder::new(reqwest_client)
        .with_init(Extension(LogName("my-client")))
        .with(LoggingMiddleware)
        .build();
    let resp = client.get("https://truelayer.com").send().await.unwrap();
    println!("TrueLayer page HTML: {}", resp.text().await.unwrap());
}

Tuple Fields

0: T

Trait Implementations

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more