-
Notifications
You must be signed in to change notification settings - Fork 14
/
client.rs
48 lines (38 loc) · 1.56 KB
/
client.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
use std::env;
use std::time::Duration;
use http_body_util::{BodyExt, Empty};
use hyper::body::Bytes;
use hyper_util::{client::legacy::Client, rt::TokioExecutor};
use tokio::io::{self, AsyncWriteExt};
use hyper_tls::HttpsConnector;
use hyper_timeout::TimeoutConnector;
#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let url = match env::args().nth(1) {
Some(url) => url,
None => {
println!("Usage: client <url>");
println!("Example: client https://example.com");
return Ok(());
}
};
let url = url.parse::<hyper::Uri>().unwrap();
// This example uses `HttpsConnector`, but you can also use hyper `HttpConnector`
//let h = hyper_util::client::legacy::connect::HttpConnector::new();
let h = HttpsConnector::new();
let mut connector = TimeoutConnector::new(h);
connector.set_connect_timeout(Some(Duration::from_secs(5)));
connector.set_read_timeout(Some(Duration::from_secs(5)));
connector.set_write_timeout(Some(Duration::from_secs(5)));
let client = Client::builder(TokioExecutor::new()).build::<_, Empty<Bytes>>(connector);
let mut res = client.get(url).await?;
println!("Status: {}", res.status());
println!("Headers:\n{:#?}", res.headers());
while let Some(frame) = res.body_mut().frame().await {
let bytes = frame?
.into_data()
.map_err(|_| io::Error::new(io::ErrorKind::Other, "Error when consuming frame"))?;
io::stdout().write_all(&bytes).await?;
}
Ok(())
}