#[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
use reqwest::Proxy;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{Client, ClientBuilder, Response};
use url::Url;
use super::builder::DispatcherBuilder;
use crate::error::Error;
use crate::payload::Payload;
#[derive(Debug, Clone)]
pub struct Async {
client: Client,
}
impl Async {
#[inline]
pub(crate) fn new(builder: DispatcherBuilder) -> Result<Self, Error> {
Self::new_with_client(builder, ClientBuilder::new())
}
pub(crate) fn new_with_client(
builder: DispatcherBuilder,
mut client: ClientBuilder,
) -> Result<Self, Error> {
if let Some(auth) = builder.auth {
let mut headers = HeaderMap::new();
let mut auth_value = HeaderValue::from_str(&auth.header_value())?;
auth_value.set_sensitive(true);
headers.insert("Authorization", auth_value);
client = client.default_headers(headers);
}
#[cfg(all(feature = "socks", not(target_arch = "wasm32")))]
if let Some(proxy) = builder.proxy {
client = client.proxy(Proxy::all(proxy)?);
}
Ok(Self {
client: client.build()?,
})
}
pub(crate) async fn send(&self, url: &Url, payload: &Payload) -> Result<(), Error> {
let mut builder = self.client.post(url.as_str());
builder = builder.json(payload);
let res: Response = builder.send().await?;
let res: Response = res.error_for_status()?;
let text: String = res.text().await?;
if text.is_empty() {
return Err(Error::EmptyResponse);
}
Ok(())
}
}