use crate::{https::get_https_client, tls, Result};
use std::io::{BufReader, Cursor, Read};
use std::sync::Arc;
use hyper::{
body::{Buf, Bytes},
client::HttpConnector,
Body, Client, Request, Response, Uri,
};
use serde::de;
pub fn is_default<T: Default + PartialEq>(t: &T) -> bool {
t == &T::default()
}
pub fn host_with_path(url: &str) -> Result<String> {
let uri: Uri = url.parse()?;
let host = uri.host().unwrap();
let path = uri.path();
Ok(format!("{}{}", host, path))
}
pub async fn into_struct_from_slice<T>(resp: Response<Body>) -> Result<T>
where
T: de::DeserializeOwned,
{
let bytes = hyper::body::to_bytes(resp).await?;
Ok(serde_json::from_slice(&bytes)?)
}
pub async fn resp_to_string(resp: &mut Response<Body>) -> Result<String> {
let body = hyper::body::aggregate(resp).await?;
let mut reader = BufReader::new(body.reader());
let mut body_string = String::new();
reader.read_to_string(&mut body_string)?;
Ok(body_string)
}
pub async fn stream_reader_from_url(
url: &str,
client: impl Into<Option<Client<tls::HttpsConnector<HttpConnector>>>>,
) -> Result<Cursor<Bytes>> {
let client = client.into().unwrap_or_else(get_https_client);
let req = Request::get(url).body(Body::empty())?;
let resp = client.request(req).await?;
let (_, body) = resp.into_parts();
let bytes = hyper::body::to_bytes(body).await?;
Ok(Cursor::new(bytes))
}
pub async fn stream_reader_from_url_and_arc_client(
url: &str,
client: Arc<Client<tls::HttpsConnector<HttpConnector>>>,
) -> Result<Cursor<Bytes>> {
let req = Request::get(url).body(Body::empty())?;
let resp = client.request(req).await?;
let (_, body) = resp.into_parts();
let bytes = hyper::body::to_bytes(body).await?;
Ok(Cursor::new(bytes))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_host_without_path() {
let url = "https://google.com";
let new_url = host_with_path(url).unwrap();
assert_eq!(new_url, "google.com/");
}
#[test]
fn test_host_and_path() {
let url = "https://google.com/my/path?key=value&key2=value2";
let new_url = host_with_path(url).unwrap();
assert_eq!(new_url, "google.com/my/path");
}
}