Expand description
Middleware types
§Examples
use crux_http::middleware::{Next, Middleware};
use crux_http::{client::Client, Request, ResponseAsync, Result};
use std::time;
use std::sync::Arc;
/// Log each request's duration
#[derive(Debug)]
pub struct Logger;
#[async_trait::async_trait]
impl Middleware for Logger {
async fn handle(
&self,
req: Request,
client: Client,
next: Next<'_>,
) -> Result<ResponseAsync> {
println!("sending request to {}", req.url());
let now = time::Instant::now();
let res = next.run(req, client).await?;
println!("request completed ({:?})", now.elapsed());
Ok(res)
}
}
Middleware
can also be instantiated using a free function thanks to some convenient trait
implementations.
use futures_util::future::BoxFuture;
use crux_http::middleware::{Next, Middleware};
use crux_http::{client::Client, Request, ResponseAsync, Result};
use std::time;
use std::sync::Arc;
fn logger<'a>(req: Request, client: Client, next: Next<'a>) -> BoxFuture<'a, Result<ResponseAsync>> {
Box::pin(async move {
println!("sending request to {}", req.url());
let now = time::Instant::now();
let res = next.run(req, client).await?;
println!("request completed ({:?})", now.elapsed());
Ok(res)
})
}
Structs§
- The remainder of a middleware chain, including the endpoint.
- A middleware which attempts to follow HTTP redirects.
Traits§
- Middleware that wraps around remaining middleware chain.