use futures_util::TryStreamExt;
use hyper::{client, Body, Chunk, Uri};
use std::str::FromStr;
use std::{env, fs, io};
fn main() {
if let Err(e) = run_client() {
eprintln!("FAILED: {}", e);
std::process::exit(1);
}
}
fn error(err: String) -> io::Error {
io::Error::new(io::ErrorKind::Other, err)
}
#[tokio::main]
async fn run_client() -> io::Result<()> {
let url = match env::args().nth(1) {
Some(ref url) => Uri::from_str(url).map_err(|e| error(format!("{}", e)))?,
None => {
println!("Usage: client <url> <ca_store>");
return Ok(());
}
};
let mut ca = match env::args().nth(2) {
Some(ref path) => {
let f = fs::File::open(path)
.map_err(|e| error(format!("failed to open {}: {}", path, e)))?;
let rd = io::BufReader::new(f);
Some(rd)
}
None => None,
};
let https = match ca {
Some(ref mut rd) => {
let mut http = client::HttpConnector::new();
http.enforce_http(false);
let mut tls = rustls::ClientConfig::new();
tls.root_store
.add_pem_file(rd)
.map_err(|_| error("failed to load custom CA store".into()))?;
hyper_rustls::HttpsConnector::from((http, tls))
}
None => hyper_rustls::HttpsConnector::new(),
};
let client: client::Client<_, hyper::Body> = client::Client::builder().build(https);
let fut = async move {
let res = client
.get(url)
.await
.map_err(|e| error(format!("Could not get: {:?}", e)))?;
println!("Status:\n{}", res.status());
println!("Headers:\n{:#?}", res.headers());
let body: Body = res.into_body();
let body: Chunk = body
.try_concat()
.await
.map_err(|e| error(format!("Could not get body: {:?}", e)))?;
println!("Body:\n{}", String::from_utf8_lossy(&body));
Ok(())
};
fut.await
}