relentless_http/
client.rs1use std::{
2 future::Future,
3 marker::PhantomData,
4 pin::Pin,
5 task::{Context, Poll},
6};
7
8use tower::Service;
9
10use relentless::error::IntoResult;
11
12pub const APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
13
14#[derive(Debug, Default)]
15pub struct DefaultHttpClient<ReqB, ResB> {
16 client: reqwest::Client,
17 phantom: PhantomData<(ReqB, ResB)>,
18}
19impl<ReqB, ResB> Clone for DefaultHttpClient<ReqB, ResB> {
20 fn clone(&self) -> Self {
21 Self { client: self.client.clone(), phantom: PhantomData }
24 }
25}
26impl<ReqB, ResB> DefaultHttpClient<ReqB, ResB> {
27 pub async fn new() -> relentless::Result<Self> {
28 let client = reqwest::Client::builder().user_agent(APP_USER_AGENT).build().box_err()?;
30 Ok(Self { client, phantom: PhantomData })
31 }
32}
33
34impl<ReqB, ResB> Service<http::Request<ReqB>> for DefaultHttpClient<ReqB, ResB>
35where
36 ReqB: Into<reqwest::Body>,
37 ResB: From<reqwest::Body>,
38{
39 type Response = http::Response<ResB>;
40 type Error = reqwest::Error;
41 type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
42
43 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
44 self.client.poll_ready(cx)
45 }
46
47 fn call(&mut self, request: http::Request<ReqB>) -> Self::Future {
48 match request.try_into() {
49 Ok(req) => {
50 let fut = self.client.call(req);
51 Box::pin(async {
52 fut.await.map(|res| {
53 let b = http::Response::<reqwest::Body>::from(res);
54 let (parts, incoming) = b.into_parts();
55 http::Response::from_parts(parts, incoming.into())
56 })
57 })
58 }
59 Err(e) => Box::pin(async { Err(e) }),
60 }
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use bytes::Bytes;
67 use tower::ServiceExt;
68
69 use super::*;
70
71 #[tokio::test]
72 async fn test_default_http_client() {
73 let server = httptest::Server::run();
74 server.expect(
75 httptest::Expectation::matching(httptest::matchers::request::method_path("GET", "/"))
76 .respond_with(httptest::responders::status_code(200).body("hello world")),
77 );
78
79 let mut client = DefaultHttpClient::<Bytes, reqwest::Body>::new().await.unwrap();
80 let request = http::Request::builder().uri(server.url("/")).body(Bytes::new()).unwrap();
81 let res: reqwest::Response = client.ready().await.unwrap().call(request).await.unwrap().into();
82 assert_eq!(res.status(), 200);
83 assert_eq!(res.text().await.unwrap(), "hello world");
84 }
85}