8 releases

0.4.0 Oct 14, 2024
0.4.0-alpha.3 Sep 12, 2024
0.4.0-alpha.1 Jun 8, 2024
0.3.2 May 5, 2024
0.2.1 Apr 21, 2024

#137 in HTTP client

Download history 14/week @ 2024-07-27 150/week @ 2024-09-07 87/week @ 2024-09-14 52/week @ 2024-09-21 80/week @ 2024-09-28 52/week @ 2024-10-05 225/week @ 2024-10-12 46/week @ 2024-10-19 29/week @ 2024-10-26 38/week @ 2024-11-02 58/week @ 2024-11-09

193 downloads per month

MIT/Apache

30KB
481 lines

tower-http-client

tests crates.io Documentation MIT/Apache-2 licensed

This library provides middlewares and various utilities for HTTP-clients.

Thus, it extends the tower_http functionality for creating HTTP clients using tower middlewares.

At the moment, the de facto standard client library is reqwest, which is poorly compatible with the tower services, but thanks to the tower_reqwest crate, it can be used with the any tower_http layers.

The first goal of the project is to create a more flexible and extensible alternative for reqwest_middleware.

Examples

Simple client usage with layers from the tower_http.

use http::{header::USER_AGENT, HeaderValue};
use tower::{ServiceBuilder, ServiceExt};
use tower_http::ServiceBuilderExt;
use tower_http_client::{ServiceExt as _, ResponseExt as _};
use tower_reqwest::HttpClientLayer;

/// Implementation agnostic HTTP client.
type HttpClient = tower::util::BoxCloneService<
    http::Request<reqwest::Body>,
    http::Response<reqwest::Body>,
    anyhow::Error,
>;

/// Creates HTTP client with Tower layers on top of the given client.
fn make_client(client: reqwest::Client) -> HttpClient {
    ServiceBuilder::new()
        // Add some layers.
        .override_request_header(USER_AGENT, HeaderValue::from_static("tower-http-client"))
        // Make client compatible with the `tower-http` layers.
        .layer(HttpClientLayer)
        .service(client)
        .map_err(anyhow::Error::from)
        .boxed_clone()
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create a new client
    let client = make_client(reqwest::Client::new());
    // Execute request by using this service.
    let response = client
        .clone()
        .get("http://ip.jsontest.com")
        .send()?
        .await?;

    let text = response.body_reader().utf8().await?;
    println!("{text}");

    Ok(())
}

Dependencies

~4–15MB
~196K SLoC