docs(examples): add some comments in the client example

This commit is contained in:
Sean McArthur
2018-05-03 12:00:34 -07:00
parent a5d2c639f5
commit a16234fa26
2 changed files with 25 additions and 14 deletions

View File

@@ -11,6 +11,7 @@ use hyper::rt::{self, Future, Stream};
fn main() {
pretty_env_logger::init();
// Some simple CLI args requirements...
let url = match env::args().nth(1) {
Some(url) => url,
None => {
@@ -19,6 +20,8 @@ fn main() {
}
};
// HTTPS requires picking a TLS implementation, so give a better
// warning if the user tries to request an 'https' URL.
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.");
@@ -28,21 +31,29 @@ fn main() {
rt::run(rt::lazy(move || {
let client = Client::new();
let mut req = Request::new(Body::empty());
*req.uri_mut() = url;
client
// Fetch the url...
.get(url)
// And then, if we get a response back...
.and_then(|res| {
println!("Response: {}", res.status());
println!("Headers: {:#?}", res.headers());
client.request(req).and_then(|res| {
println!("Response: {}", res.status());
println!("Headers: {:#?}", res.headers());
res.into_body().for_each(|chunk| {
io::stdout().write_all(&chunk)
.map_err(|e| panic!("example expects stdout is open, error={}", e))
// The body is a stream, and for_each returns a new Future
// when the stream is finished, and calls the closure on
// each chunk of the body...
res.into_body().for_each(|chunk| {
io::stdout().write_all(&chunk)
.map_err(|e| panic!("example expects stdout is open, error={}", e))
})
})
// If all good, just tell the user...
.map(|_| {
println!("\n\nDone.");
})
// If there was an error, let the user know...
.map_err(|err| {
eprintln!("Error {}", err);
})
}).map(|_| {
println!("\n\nDone.");
}).map_err(|err| {
eprintln!("Error {}", err);
})
}));
}