pub struct HttpClientLayer;Available on crate feature
reqwest only.Expand description
Layer that creates HttpClientService from the inner service.
§Examples
This library provides adapters to use reqwest client with the tower_http layers.
§Example
use http::{header::USER_AGENT, HeaderValue};
use http_body_util::BodyExt;
use serde_json::{json, Value};
use tower::{Service, ServiceBuilder};
use tower_http::ServiceBuilderExt;
use tower_reqwest::HttpClientLayer;
use wiremock::{matchers, Mock, MockServer, ResponseTemplate};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let mock_server = MockServer::start().await;
let mock_uri = mock_server.uri();
// Create a mock server that will respond to a GET request on `/test`.
Mock::given(matchers::method("GET"))
.and(matchers::path("/hello"))
.respond_with(ResponseTemplate::new(200).set_body_json(json!({ "value": "Hello world" })))
.mount(&mock_server)
.await;
let mut client = ServiceBuilder::new()
// Add some layers.
.override_request_header(USER_AGENT, HeaderValue::from_static("tower-reqwest"))
// Make client compatible with the `tower-http` layers.
.layer(HttpClientLayer)
.service(reqwest::Client::new());
// Execute request by using this service.
let response = client
.call(
http::request::Builder::new()
.method(http::Method::GET)
.uri(format!("{mock_uri}/hello"))
.body(reqwest::Body::default())?,
)
.await?;
let bytes = response.into_body().collect().await?.to_bytes();
let value: Value = serde_json::from_slice(&bytes)?;
println!("{value:#?}");
Ok(())
}Trait Implementations§
Source§impl Clone for HttpClientLayer
impl Clone for HttpClientLayer
Source§fn clone(&self) -> HttpClientLayer
fn clone(&self) -> HttpClientLayer
Returns a duplicate of the value. Read more
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
Performs copy-assignment from
source. Read moreSource§impl Debug for HttpClientLayer
impl Debug for HttpClientLayer
Source§impl<S> Layer<S> for HttpClientLayer
impl<S> Layer<S> for HttpClientLayer
Source§type Service = HttpClientService<S>
type Service = HttpClientService<S>
The wrapped service
impl Copy for HttpClientLayer
Auto Trait Implementations§
impl Freeze for HttpClientLayer
impl RefUnwindSafe for HttpClientLayer
impl Send for HttpClientLayer
impl Sync for HttpClientLayer
impl Unpin for HttpClientLayer
impl UnwindSafe for HttpClientLayer
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more