2023-11-06 09:14:46 -05:00
|
|
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
|
|
|
|
#![doc = include_str!("../README.md")]
|
|
|
|
|
|
|
|
|
|
use hyper_rustls::{HttpsConnectorBuilder, HttpsConnector};
|
2023-11-06 10:31:26 -05:00
|
|
|
use hyper::{header::HeaderValue, client::HttpConnector};
|
|
|
|
|
pub use hyper;
|
|
|
|
|
|
|
|
|
|
mod request;
|
|
|
|
|
pub use request::*;
|
|
|
|
|
|
|
|
|
|
mod response;
|
|
|
|
|
pub use response::*;
|
2023-11-06 09:14:46 -05:00
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
2023-11-06 10:31:26 -05:00
|
|
|
pub enum Error {
|
|
|
|
|
InvalidUri,
|
|
|
|
|
Hyper(hyper::Error),
|
2023-11-06 09:14:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
enum Connection {
|
|
|
|
|
ConnectionPool(hyper::Client<HttpsConnector<HttpConnector>>),
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[derive(Clone, Debug)]
|
|
|
|
|
pub struct Client {
|
|
|
|
|
connection: Connection,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl Client {
|
|
|
|
|
fn https_builder() -> HttpsConnector<HttpConnector> {
|
|
|
|
|
HttpsConnectorBuilder::new().with_native_roots().https_or_http().enable_http1().build()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn with_connection_pool() -> Client {
|
|
|
|
|
Client {
|
|
|
|
|
connection: Connection::ConnectionPool(hyper::Client::builder().build(Self::https_builder())),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
fn without_connection_pool() -> Client {}
|
|
|
|
|
*/
|
|
|
|
|
|
2023-11-06 10:31:26 -05:00
|
|
|
pub async fn request<R: Into<Request>>(&self, request: R) -> Result<Response, Error> {
|
|
|
|
|
let request: Request = request.into();
|
|
|
|
|
let mut request = request.0;
|
2023-11-06 09:14:46 -05:00
|
|
|
if request.headers().get(hyper::header::HOST).is_none() {
|
2023-11-06 10:31:26 -05:00
|
|
|
let host = request.uri().host().ok_or(Error::InvalidUri)?.to_string();
|
2023-11-06 09:14:46 -05:00
|
|
|
request
|
|
|
|
|
.headers_mut()
|
2023-11-06 10:31:26 -05:00
|
|
|
.insert(hyper::header::HOST, HeaderValue::from_str(&host).map_err(|_| Error::InvalidUri)?);
|
2023-11-06 09:14:46 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(Response(match &self.connection {
|
|
|
|
|
Connection::ConnectionPool(client) => client.request(request).await.map_err(Error::Hyper)?,
|
|
|
|
|
}))
|
|
|
|
|
}
|
|
|
|
|
}
|