doc(client): show spawning a client future, clarify lazy in client example

This commit is contained in:
Sean McArthur
2018-06-18 17:02:57 -07:00
parent 482a5f589e
commit 61f31b5a4a
2 changed files with 72 additions and 61 deletions

View File

@@ -28,32 +28,38 @@ fn main() {
return; return;
} }
rt::run(rt::lazy(move || { // Run the runtime with the future trying to fetch and print this URL.
let client = Client::new(); //
// Note that in more complicated use cases, the runtime should probably
client // run on its own, and futures should just be spawned into it.
// Fetch the url... rt::run(fetch_url(url));
.get(url) }
// And then, if we get a response back...
.and_then(|res| { fn fetch_url(url: hyper::Uri) -> impl Future<Item=(), Error=()> {
println!("Response: {}", res.status()); let client = Client::new();
println!("Headers: {:#?}", res.headers());
client
// The body is a stream, and for_each returns a new Future // Fetch the url...
// when the stream is finished, and calls the closure on .get(url)
// each chunk of the body... // And then, if we get a response back...
res.into_body().for_each(|chunk| { .and_then(|res| {
io::stdout().write_all(&chunk) println!("Response: {}", res.status());
.map_err(|e| panic!("example expects stdout is open, error={}", e)) println!("Headers: {:#?}", res.headers());
})
}) // The body is a stream, and for_each returns a new Future
// If all good, just tell the user... // when the stream is finished, and calls the closure on
.map(|_| { // each chunk of the body...
println!("\n\nDone."); res.into_body().for_each(|chunk| {
}) io::stdout().write_all(&chunk)
// If there was an error, let the user know... .map_err(|e| panic!("example expects stdout is open, error={}", e))
.map_err(|err| { })
eprintln!("Error {}", err); })
}) // 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);
})
} }

View File

@@ -23,52 +23,57 @@
//! //!
//! ## Example //! ## Example
//! //!
//! ```no_run //! For a small example program simply fetching a URL, take a look at the
//! [full client example](https://github.com/hyperium/hyper/blob/master/examples/client.rs).
//!
//! ```
//! extern crate hyper; //! extern crate hyper;
//! //!
//! use hyper::Client; //! use hyper::Client;
//! # #[cfg(feature = "runtime")] //! # #[cfg(feature = "runtime")]
//! use hyper::rt::{self, lazy, Future, Stream}; //! use hyper::rt::{self, Future, Stream};
//! //!
//! # #[cfg(feature = "runtime")] //! # #[cfg(feature = "runtime")]
//! fn main() { //! # fn fetch_httpbin() {
//! // A runtime is needed to execute our asynchronous code. //! let client = Client::new();
//! rt::run(lazy(|| {
//! let client = Client::new();
//! //!
//! client //! let fut = client
//! // Make a GET /ip to 'http://httpbin.org'
//! .get("http://httpbin.org/ip".parse().unwrap())
//! //!
//! // And then, if the request gets a response... //! // Make a GET /ip to 'http://httpbin.org'
//! .and_then(|res| { //! .get("http://httpbin.org/ip".parse().unwrap())
//! println!("status: {}", res.status());
//! //!
//! // Concatenate the body stream into a single buffer... //! // And then, if the request gets a response...
//! // This returns a new future, since we must stream body. //! .and_then(|res| {
//! res.into_body().concat2() //! println!("status: {}", res.status());
//! })
//! //!
//! // And then, if reading the full body succeeds... //! // Concatenate the body stream into a single buffer...
//! .and_then(|body| { //! // This returns a new future, since we must stream body.
//! // The body is just bytes, but let's print a string... //! res.into_body().concat2()
//! let s = ::std::str::from_utf8(&body) //! })
//! .expect("httpbin sends utf-8 JSON");
//! //!
//! println!("body: {}", s); //! // And then, if reading the full body succeeds...
//! .and_then(|body| {
//! // The body is just bytes, but let's print a string...
//! let s = ::std::str::from_utf8(&body)
//! .expect("httpbin sends utf-8 JSON");
//! //!
//! // and_then requires we return a new Future, and it turns //! println!("body: {}", s);
//! // out that Result is a Future that is ready immediately.
//! Ok(())
//! })
//! //!
//! // Map any errors that might have happened... //! // and_then requires we return a new Future, and it turns
//! .map_err(|err| { //! // out that Result is a Future that is ready immediately.
//! println!("error: {}", err); //! Ok(())
//! }) //! })
//! })); //!
//! } //! // Map any errors that might have happened...
//! # #[cfg(not(feature = "runtime"))] //! .map_err(|err| {
//! println!("error: {}", err);
//! });
//!
//! // A runtime is needed to execute our asynchronous code. In order to
//! // spawn the future into the runtime, it should already have been
//! // started and running before calling this this code.
//! rt::spawn(fut);
//! # }
//! # fn main () {} //! # fn main () {}
//! ``` //! ```