Merge pull request #99 from jaemk/update_examples

update example error handling
This commit is contained in:
Sean McArthur
2017-05-23 23:26:48 -05:00
committed by GitHub
7 changed files with 131 additions and 50 deletions

View File

@@ -22,3 +22,4 @@ libflate = "0.1.5"
[dev-dependencies] [dev-dependencies]
env_logger = "0.4" env_logger = "0.4"
serde_derive = "1.0" serde_derive = "1.0"
error-chain = "0.10"

View File

@@ -1,15 +1,24 @@
// cargo run --example response_json //! `cargo run --example response_json`
extern crate reqwest; extern crate reqwest;
#[macro_use] extern crate serde_derive;
#[macro_use] extern crate error_chain;
#[macro_use] error_chain! {
extern crate serde_derive; foreign_links {
ReqError(reqwest::Error);
}
}
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
struct Response { struct Response {
origin: String, origin: String,
} }
fn main() { fn run() -> Result<()> {
let mut res = reqwest::get("https://httpbin.org/ip").unwrap(); let mut res = reqwest::get("https://httpbin.org/ip")?;
println!("JSON: {:?}", res.json::<Response>()); let json = res.json::<Response>()?;
println!("JSON: {:?}", json);
Ok(())
} }
quick_main!(run);

View File

@@ -1,17 +1,31 @@
//! `cargo run --example simple`
extern crate reqwest; extern crate reqwest;
extern crate env_logger; extern crate env_logger;
#[macro_use] extern crate error_chain;
fn main() { error_chain! {
env_logger::init().unwrap(); foreign_links {
ReqError(reqwest::Error);
IoError(std::io::Error);
}
}
fn run() -> Result<()> {
env_logger::init()
.expect("Failed to initialize logger");
println!("GET https://www.rust-lang.org"); println!("GET https://www.rust-lang.org");
let mut res = reqwest::get("https://www.rust-lang.org").unwrap(); let mut res = reqwest::get("https://www.rust-lang.org")?;
println!("Status: {}", res.status()); println!("Status: {}", res.status());
println!("Headers:\n{}", res.headers()); println!("Headers:\n{}", res.headers());
::std::io::copy(&mut res, &mut ::std::io::stdout()).unwrap(); // copy the response body directly to stdout
let _ = std::io::copy(&mut res, &mut std::io::stdout())?;
println!("\n\nDone."); println!("\n\nDone.");
Ok(())
} }
quick_main!(run);

View File

@@ -31,7 +31,7 @@ static DEFAULT_USER_AGENT: &'static str = concat!(env!("CARGO_PKG_NAME"), "/", e
/// ///
/// # Examples /// # Examples
/// ///
/// ``` /// ```rust
/// # use reqwest::{Error, Client}; /// # use reqwest::{Error, Client};
/// # /// #
/// # fn run() -> Result<(), Error> { /// # fn run() -> Result<(), Error> {
@@ -182,13 +182,18 @@ pub struct RequestBuilder {
impl RequestBuilder { impl RequestBuilder {
/// Add a `Header` to this Request. /// Add a `Header` to this Request.
/// ///
/// ```no_run /// ```rust
/// # use reqwest::Error;
/// #
/// # fn run() -> Result<(), Error> {
/// use reqwest::header::UserAgent; /// 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") /// let res = client.get("https://www.rust-lang.org")
/// .header(UserAgent("foo".to_string())) /// .header(UserAgent("foo".to_string()))
/// .send(); /// .send()?;
/// # Ok(())
/// # }
/// ``` /// ```
pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder { pub fn header<H: ::header::Header + ::header::HeaderFormat>(mut self, header: H) -> RequestBuilder {
self.headers.set(header); self.headers.set(header);
@@ -222,15 +227,20 @@ impl RequestBuilder {
/// and also sets the `Content-Type: application/www-form-url-encoded` /// and also sets the `Content-Type: application/www-form-url-encoded`
/// header. /// header.
/// ///
/// ```no_run /// ```rust
/// # use reqwest::Error;
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// #
/// # fn run() -> Result<(), Error> {
/// let mut params = HashMap::new(); /// let mut params = HashMap::new();
/// params.insert("lang", "rust"); /// params.insert("lang", "rust");
/// ///
/// let client = reqwest::Client::new().unwrap(); /// let client = reqwest::Client::new()?;
/// let res = client.post("http://httpbin.org") /// let res = client.post("http://httpbin.org")
/// .form(&params) /// .form(&params)
/// .send(); /// .send()?;
/// # Ok(())
/// # }
/// ``` /// ```
pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder { pub fn form<T: Serialize>(mut self, form: &T) -> RequestBuilder {
let body = serde_urlencoded::to_string(form).map_err(::error::from); 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 /// Sets the body to the JSON serialization of the passed value, and
/// also sets the `Content-Type: application/json` header. /// also sets the `Content-Type: application/json` header.
/// ///
/// ```no_run /// ```rust
/// # use reqwest::Error;
/// # use std::collections::HashMap; /// # use std::collections::HashMap;
/// #
/// # fn run() -> Result<(), Error> {
/// let mut map = HashMap::new(); /// let mut map = HashMap::new();
/// map.insert("lang", "rust"); /// map.insert("lang", "rust");
/// ///
/// let client = reqwest::Client::new().unwrap(); /// let client = reqwest::Client::new()?;
/// let res = client.post("http://httpbin.org") /// let res = client.post("http://httpbin.org")
/// .json(&map) /// .json(&map)
/// .send(); /// .send()?;
/// # Ok(())
/// # }
/// ``` /// ```
pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder { pub fn json<T: Serialize>(mut self, json: &T) -> RequestBuilder {
let body = serde_json::to_vec(json).expect("serde to_vec cannot fail"); let body = serde_json::to_vec(json).expect("serde to_vec cannot fail");

View File

@@ -49,11 +49,16 @@
//! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom //! including `String`, `Vec<u8>`, and `File`. If you wish to pass a custom
//! Reader, you can use the `reqwest::Body::new()` constructor. //! Reader, you can use the `reqwest::Body::new()` constructor.
//! //!
//! ```no_run //! ```rust
//! let client = reqwest::Client::new().unwrap(); //! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! let client = reqwest::Client::new()?;
//! let res = client.post("http://httpbin.org/post") //! let res = client.post("http://httpbin.org/post")
//! .body("the exact body that is sent") //! .body("the exact body that is sent")
//! .send(); //! .send()?;
//! # Ok(())
//! # }
//! ``` //! ```
//! //!
//! ### Forms //! ### Forms
@@ -64,13 +69,18 @@
//! This can be an array of tuples, or a `HashMap`, or a custom type that //! This can be an array of tuples, or a `HashMap`, or a custom type that
//! implements [`Serialize`][serde]. //! implements [`Serialize`][serde].
//! //!
//! ```no_run //! ```rust
//! # use reqwest::Error;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `foo=bar&baz=quux` //! // This will POST a body of `foo=bar&baz=quux`
//! let params = [("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") //! let res = client.post("http://httpbin.org/post")
//! .form(&params) //! .form(&params)
//! .send(); //! .send()?;
//! # Ok(())
//! # }
//! ``` //! ```
//! //!
//! ### JSON //! ### JSON
@@ -79,17 +89,22 @@
//! a similar fashion the `form` method. It can take any value that can be //! a similar fashion the `form` method. It can take any value that can be
//! serialized into JSON. //! serialized into JSON.
//! //!
//! ```no_run //! ```rust
//! # use reqwest::Error;
//! # use std::collections::HashMap; //! # use std::collections::HashMap;
//! #
//! # fn run() -> Result<(), Error> {
//! // This will POST a body of `{"lang":"rust","body":"json"}` //! // This will POST a body of `{"lang":"rust","body":"json"}`
//! let mut map = HashMap::new(); //! let mut map = HashMap::new();
//! map.insert("lang", "rust"); //! map.insert("lang", "rust");
//! map.insert("body", "json"); //! map.insert("body", "json");
//! //!
//! let client = reqwest::Client::new().unwrap(); //! let client = reqwest::Client::new()?;
//! let res = client.post("http://httpbin.org/post") //! let res = client.post("http://httpbin.org/post")
//! .json(&map) //! .json(&map)
//! .send(); //! .send()?;
//! # Ok(())
//! # }
//! ``` //! ```
//! //!
//! [hyper]: http://hyper.rs //! [hyper]: http://hyper.rs
@@ -159,12 +174,31 @@ mod response;
/// ///
/// # Examples /// # Examples
/// ///
/// ```no_run /// ```rust
/// # extern crate reqwest;
/// # #[macro_use] extern crate error_chain;
/// #
/// use std::io::Read; /// use std::io::Read;
/// ///
/// # error_chain! {
/// # foreign_links {
/// # Reqwest(reqwest::Error);
/// # Io(std::io::Error);
/// # }
/// # }
/// #
/// # fn run() -> Result<()> {
/// let mut result = String::new(); /// let mut result = String::new();
/// reqwest::get("https://www.rust-lang.org").unwrap() /// reqwest::get("https://www.rust-lang.org")?
/// .read_to_string(&mut result); /// .read_to_string(&mut result)?;
/// # Ok(())
/// # }
/// #
/// # fn main() {
/// # if let Err(error) = run() {
/// # println!("Error: {:?}", error);
/// # }
/// # }
/// ``` /// ```
pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> { pub fn get<T: IntoUrl>(url: T) -> ::Result<Response> {
let client = try!(Client::new()); let client = try!(Client::new());

View File

@@ -58,9 +58,11 @@ impl RedirectPolicy {
/// ///
/// # Example /// # Example
/// ///
/// ```no_run /// ```rust
/// # use reqwest::RedirectPolicy; /// # use reqwest::{Error, RedirectPolicy};
/// # let mut client = reqwest::Client::new().unwrap(); /// #
/// # fn run() -> Result<(), Error> {
/// let mut client = reqwest::Client::new()?;
/// client.redirect(RedirectPolicy::custom(|attempt| { /// client.redirect(RedirectPolicy::custom(|attempt| {
/// if attempt.previous().len() > 5 { /// if attempt.previous().len() > 5 {
/// attempt.too_many_redirects() /// attempt.too_many_redirects()
@@ -71,6 +73,8 @@ impl RedirectPolicy {
/// attempt.follow() /// attempt.follow()
/// } /// }
/// })); /// }));
/// # Ok(())
/// # }
/// ``` /// ```
pub fn custom<T>(policy: T) -> RedirectPolicy pub fn custom<T>(policy: T) -> RedirectPolicy
where T: Fn(RedirectAttempt) -> RedirectAction + Send + Sync + 'static { where T: Fn(RedirectAttempt) -> RedirectAction + Send + Sync + 'static {

View File

@@ -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 /// # Examples
/// ///
/// ```rust,no_run /// ```rust
/// extern crate reqwest; /// # extern crate reqwest;
/// #[macro_use] /// # #[macro_use] extern crate serde_derive;
/// extern crate serde_derive; /// #
/// /// # use reqwest::Error;
/// #
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct User { /// struct Response {
/// name: String, /// origin: String,
/// age: u8,
/// } /// }
/// ///
/// fn main() { /// # fn run() -> Result<(), Error> {
/// let user: User = reqwest::get("http://127.0.0.1/user.json") /// let resp: Response = reqwest::get("http://127.0.0.1/user.json")?.json()?;
/// .expect("network error") /// # Ok(())
/// .json() /// # }
/// .expect("malformed json"); /// #
/// } /// # fn main() {
/// # if let Err(error) = run() {
/// # println!("Error: {:?}", error);
/// # }
/// # }
/// ``` /// ```
#[inline] #[inline]
pub fn json<T: DeserializeOwned>(&mut self) -> ::Result<T> { pub fn json<T: DeserializeOwned>(&mut self) -> ::Result<T> {