docs(examples): update client example to use rt::main
This commit is contained in:
@@ -7,9 +7,12 @@ use std::env;
|
||||
use std::io::{self, Write};
|
||||
|
||||
use hyper::Client;
|
||||
use hyper::rt;
|
||||
|
||||
fn main() {
|
||||
// A simple type alias so as to DRY.
|
||||
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
|
||||
|
||||
#[hyper::rt::main]
|
||||
async fn main() -> Result<()> {
|
||||
pretty_env_logger::init();
|
||||
|
||||
// Some simple CLI args requirements...
|
||||
@@ -17,7 +20,7 @@ fn main() {
|
||||
Some(url) => url,
|
||||
None => {
|
||||
println!("Usage: client <url>");
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -26,26 +29,16 @@ fn main() {
|
||||
let url = url.parse::<hyper::Uri>().unwrap();
|
||||
if url.scheme_part().map(|s| s.as_ref()) != Some("http") {
|
||||
println!("This example only works with 'http' URLs.");
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Run the runtime with the future trying to fetch and print this URL.
|
||||
//
|
||||
// Note that in more complicated use cases, the runtime should probably
|
||||
// run on its own, and futures should just be spawned into it.
|
||||
rt::run(fetch_url(url));
|
||||
fetch_url(url).await
|
||||
}
|
||||
|
||||
async fn fetch_url(url: hyper::Uri) {
|
||||
async fn fetch_url(url: hyper::Uri) -> Result<()> {
|
||||
let client = Client::new();
|
||||
|
||||
let res = match client.get(url).await {
|
||||
Ok(res) => res,
|
||||
Err(err) => {
|
||||
eprintln!("Response Error: {}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let res = client.get(url).await?;
|
||||
|
||||
println!("Response: {}", res.status());
|
||||
println!("Headers: {:#?}\n", res.headers());
|
||||
@@ -53,17 +46,11 @@ async fn fetch_url(url: hyper::Uri) {
|
||||
let mut body = res.into_body();
|
||||
|
||||
while let Some(next) = body.next().await {
|
||||
match next {
|
||||
Ok(chunk) => {
|
||||
io::stdout().write_all(&chunk)
|
||||
.expect("example expects stdout is open");
|
||||
},
|
||||
Err(err) => {
|
||||
eprintln!("Body Error: {}", err);
|
||||
return;
|
||||
}
|
||||
}
|
||||
let chunk = next?;
|
||||
io::stdout().write_all(&chunk)?;
|
||||
}
|
||||
|
||||
println!("\n\nDone!");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user