From 812c220e6180befadbb7d427ed176e782662c08e Mon Sep 17 00:00:00 2001 From: James Kominick Date: Sun, 21 May 2017 17:14:32 -0400 Subject: [PATCH] update doc examples - Make examples runnable for doc tests - Add error handling using `?` instead of `unwrap` --- src/client.rs | 35 ++++++++++++++++++++--------- src/lib.rs | 58 +++++++++++++++++++++++++++++++++++++++---------- src/redirect.rs | 10 ++++++--- src/response.rs | 34 ++++++++++++++++------------- 4 files changed, 97 insertions(+), 40 deletions(-) diff --git a/src/client.rs b/src/client.rs index 63d83c6..a5c5f36 100644 --- a/src/client.rs +++ b/src/client.rs @@ -31,7 +31,7 @@ static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", e /// /// # Examples /// -/// ``` +/// ```rust /// # use reqwest::{Error, Client}; /// # /// # fn run() -> Result<(), Error> { @@ -182,13 +182,18 @@ pub struct RequestBuilder { impl RequestBuilder { /// Add a `Header` to this Request. /// - /// ```no_run + /// ```rust + /// # use reqwest::Error; + /// # + /// # fn run() -> Result<(), Error> { /// use reqwest::header::UserAgent; - /// let client = reqwest::Client::new().expect("client failed to construct"); + /// let client = reqwest::Client::new()?; /// /// let res = client.get("https://www.rust-lang.org") /// .header(UserAgent("foo".to_string())) - /// .send(); + /// .send()?; + /// # Ok(()) + /// # } /// ``` pub fn header(mut self, header: H) -> RequestBuilder { self.headers.set(header); @@ -222,15 +227,20 @@ impl RequestBuilder { /// and also sets the `Content-Type: application/www-form-url-encoded` /// header. /// - /// ```no_run + /// ```rust + /// # use reqwest::Error; /// # use std::collections::HashMap; + /// # + /// # fn run() -> Result<(), Error> { /// let mut params = HashMap::new(); /// params.insert("lang", "rust"); /// - /// let client = reqwest::Client::new().unwrap(); + /// let client = reqwest::Client::new()?; /// let res = client.post("http://httpbin.org") /// .form(¶ms) - /// .send(); + /// .send()?; + /// # Ok(()) + /// # } /// ``` pub fn form(mut self, form: &T) -> RequestBuilder { let body = serde_urlencoded::to_string(form).map_err(::error::from); @@ -244,15 +254,20 @@ impl RequestBuilder { /// Sets the body to the JSON serialization of the passed value, and /// also sets the `Content-Type: application/json` header. /// - /// ```no_run + /// ```rust + /// # use reqwest::Error; /// # use std::collections::HashMap; + /// # + /// # fn run() -> Result<(), Error> { /// let mut map = HashMap::new(); /// map.insert("lang", "rust"); /// - /// let client = reqwest::Client::new().unwrap(); + /// let client = reqwest::Client::new()?; /// let res = client.post("http://httpbin.org") /// .json(&map) - /// .send(); + /// .send()?; + /// # Ok(()) + /// # } /// ``` pub fn json(mut self, json: &T) -> RequestBuilder { let body = serde_json::to_vec(json).expect("serde to_vec cannot fail"); diff --git a/src/lib.rs b/src/lib.rs index f8a7696..6a2c4d2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -49,11 +49,16 @@ //! including `String`, `Vec`, and `File`. If you wish to pass a custom //! Reader, you can use the `reqwest::Body::new()` constructor. //! -//! ```no_run -//! let client = reqwest::Client::new().unwrap(); +//! ```rust +//! # use reqwest::Error; +//! # +//! # fn run() -> Result<(), Error> { +//! let client = reqwest::Client::new()?; //! let res = client.post("http://httpbin.org/post") //! .body("the exact body that is sent") -//! .send(); +//! .send()?; +//! # Ok(()) +//! # } //! ``` //! //! ### Forms @@ -64,13 +69,18 @@ //! This can be an array of tuples, or a `HashMap`, or a custom type that //! implements [`Serialize`][serde]. //! -//! ```no_run +//! ```rust +//! # use reqwest::Error; +//! # +//! # fn run() -> Result<(), Error> { //! // This will POST a body of `foo=bar&baz=quux` //! let params = [("foo", "bar"), ("baz", "quux")]; -//! let client = reqwest::Client::new().unwrap(); +//! let client = reqwest::Client::new()?; //! let res = client.post("http://httpbin.org/post") //! .form(¶ms) -//! .send(); +//! .send()?; +//! # Ok(()) +//! # } //! ``` //! //! ### JSON @@ -79,17 +89,22 @@ //! a similar fashion the `form` method. It can take any value that can be //! serialized into JSON. //! -//! ```no_run +//! ```rust +//! # use reqwest::Error; //! # use std::collections::HashMap; +//! # +//! # fn run() -> Result<(), Error> { //! // This will POST a body of `{"lang":"rust","body":"json"}` //! let mut map = HashMap::new(); //! map.insert("lang", "rust"); //! map.insert("body", "json"); //! -//! let client = reqwest::Client::new().unwrap(); +//! let client = reqwest::Client::new()?; //! let res = client.post("http://httpbin.org/post") //! .json(&map) -//! .send(); +//! .send()?; +//! # Ok(()) +//! # } //! ``` //! //! [hyper]: http://hyper.rs @@ -159,12 +174,31 @@ mod response; /// /// # Examples /// -/// ```no_run +/// ```rust +/// # extern crate reqwest; +/// # #[macro_use] extern crate error_chain; +/// # /// use std::io::Read; /// +/// # error_chain! { +/// # foreign_links { +/// # Reqwest(reqwest::Error); +/// # Io(std::io::Error); +/// # } +/// # } +/// # +/// # fn run() -> Result<()> { /// let mut result = String::new(); -/// reqwest::get("https://www.rust-lang.org").unwrap() -/// .read_to_string(&mut result); +/// reqwest::get("https://www.rust-lang.org")? +/// .read_to_string(&mut result)?; +/// # Ok(()) +/// # } +/// # +/// # fn main() { +/// # if let Err(error) = run() { +/// # println!("Error: {:?}", error); +/// # } +/// # } /// ``` pub fn get(url: T) -> ::Result { let client = try!(Client::new()); diff --git a/src/redirect.rs b/src/redirect.rs index 3b71f10..695cf3c 100644 --- a/src/redirect.rs +++ b/src/redirect.rs @@ -58,9 +58,11 @@ impl RedirectPolicy { /// /// # Example /// - /// ```no_run - /// # use reqwest::RedirectPolicy; - /// # let mut client = reqwest::Client::new().unwrap(); + /// ```rust + /// # use reqwest::{Error, RedirectPolicy}; + /// # + /// # fn run() -> Result<(), Error> { + /// let mut client = reqwest::Client::new()?; /// client.redirect(RedirectPolicy::custom(|attempt| { /// if attempt.previous().len() > 5 { /// attempt.too_many_redirects() @@ -71,6 +73,8 @@ impl RedirectPolicy { /// attempt.follow() /// } /// })); + /// # Ok(()) + /// # } /// ``` pub fn custom(policy: T) -> RedirectPolicy where T: Fn(RedirectAttempt) -> RedirectAction + Send + Sync + 'static { diff --git a/src/response.rs b/src/response.rs index ed909e0..21906de 100644 --- a/src/response.rs +++ b/src/response.rs @@ -87,27 +87,31 @@ impl Response { } } - /// Try and deserialize the response body as JSON. + /// Try and deserialize the response body as JSON using `serde`. /// /// # Examples /// - /// ```rust,no_run - /// extern crate reqwest; - /// #[macro_use] - /// extern crate serde_derive; - /// + /// ```rust + /// # extern crate reqwest; + /// # #[macro_use] extern crate serde_derive; + /// # + /// # use reqwest::Error; + /// # /// #[derive(Deserialize)] - /// struct User { - /// name: String, - /// age: u8, + /// struct Response { + /// origin: String, /// } /// - /// fn main() { - /// let user: User = reqwest::get("http://127.0.0.1/user.json") - /// .expect("network error") - /// .json() - /// .expect("malformed json"); - /// } + /// # fn run() -> Result<(), Error> { + /// let resp: Response = reqwest::get("http://127.0.0.1/user.json")?.json()?; + /// # Ok(()) + /// # } + /// # + /// # fn main() { + /// # if let Err(error) = run() { + /// # println!("Error: {:?}", error); + /// # } + /// # } /// ``` #[inline] pub fn json(&mut self) -> ::Result {