Files
hyper/examples/client.rs
Sean McArthur 5d3c472228 feat(error): revamp hyper::Error type
**The `Error` is now an opaque struct**, which allows for more variants to
be added freely, and the internal representation to change without being
breaking changes.

For inspecting an `Error`, there are several `is_*` methods to check for
certain classes of errors, such as `Error::is_parse()`. The `cause` can
also be inspected, like before. This likely seems like a downgrade, but
more inspection can be added as needed!

The `Error` now knows about more states, which gives much more context
around when a certain error occurs. This is also expressed in the
description and `fmt` messages.

**Most places where a user would provide an error to hyper can now pass
any error type** (`E: Into<Box<std::error::Error>>`). This error is passed
back in relevant places, and can be useful for logging. This should make
it much clearer about what error a user should provide to hyper: any it
feels is relevant!

Closes #1128
Closes #1130
Closes #1431
Closes #1338

BREAKING CHANGE: `Error` is no longer an enum to pattern match over, or
  to construct. Code will need to be updated accordingly.

  For body streams or `Service`s, inference might be unable to determine
  what error type you mean to return. Starting in Rust 1.26, you could
  just label that as `!` if you never return an error.
2018-04-10 14:29:34 -07:00

54 lines
1.3 KiB
Rust

//#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate tokio;
extern crate pretty_env_logger;
use std::env;
use std::io::{self, Write};
use futures::{Future, Stream};
use futures::future::lazy;
use hyper::{Body, Client, Request};
fn main() {
pretty_env_logger::init();
let url = match env::args().nth(1) {
Some(url) => url,
None => {
println!("Usage: client <url>");
return;
}
};
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;
}
tokio::run(lazy(move || {
let client = Client::default();
let mut req = Request::new(Body::empty());
*req.uri_mut() = url;
client.request(req).and_then(|res| {
println!("Response: {}", res.status());
println!("Headers: {:#?}", res.headers());
res.into_body().into_stream().for_each(|chunk| {
io::stdout().write_all(&chunk)
.map_err(|e| panic!("example expects stdout is open, error={}", e))
})
}).map(|_| {
println!("\n\nDone.");
}).map_err(|err| {
eprintln!("Error {}", err);
})
}));
}