Skip to content

Instantly share code, notes, and snippets.

@gsquire
Last active November 17, 2016 22:19
Show Gist options
  • Save gsquire/c97d09cd49083bada6bed0c11848bd01 to your computer and use it in GitHub Desktop.
Save gsquire/c97d09cd49083bada6bed0c11848bd01 to your computer and use it in GitHub Desktop.
diff --git a/Cargo.toml b/Cargo.toml
index 633e404..6963348 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -12,6 +12,7 @@ license = "MIT/Apache-2.0"
hyper = { version = "0.9" , default-features = false }
log = "0.3"
native-tls = "0.1"
+serde_derive = "0.8"
serde = "0.8"
serde_json = "0.8"
serde_urlencoded = "0.3"
diff --git a/examples/simple.rs b/examples/simple.rs
index b891524..b2a9d2e 100644
--- a/examples/simple.rs
+++ b/examples/simple.rs
@@ -1,17 +1,16 @@
+#![feature(proc_macro)]
extern crate reqwest;
-extern crate env_logger;
-fn main() {
- env_logger::init().unwrap();
-
- println!("GET https://www.rust-lang.org");
-
- let mut res = reqwest::get("https://www.rust-lang.org").unwrap();
+#[macro_use]
+extern crate serde_derive;
- println!("Status: {}", res.status());
- println!("Headers:\n{}", res.headers());
+#[derive(Debug, Deserialize)]
+struct Something {
+ Origin: String,
+}
- ::std::io::copy(&mut res, &mut ::std::io::stdout()).unwrap();
+fn main() {
+ let mut res = reqwest::get("https://httpbin.org/user-agent").unwrap();
- println!("\n\nDone.");
+ println!("JSON: {:?}", res.json::<Something>());
}
diff --git a/src/client.rs b/src/client.rs
index 8f20346..fba027a 100644
--- a/src/client.rs
+++ b/src/client.rs
@@ -7,7 +7,7 @@ use hyper::status::StatusCode;
use hyper::version::HttpVersion;
use hyper::{Url};
-use serde::Serialize;
+use serde::{Deserialize, Serialize};
use serde_json;
use serde_urlencoded;
@@ -275,6 +275,11 @@ impl Response {
pub fn version(&self) -> &HttpVersion {
&self.inner.version
}
+
+ /// Try and deserialize the response body as JSON.
+ pub fn json<T: Deserialize>(&mut self) -> ::Result<T> {
+ serde_json::from_reader(self).map_err(::Error::from)
+ }
}
/// Read the body of the Response.
diff --git a/src/error.rs b/src/error.rs
index e78c13c..9b67d91 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -13,6 +13,8 @@ pub enum Error {
Serialize(Box<StdError>),
/// A request tried to redirect too many times.
TooManyRedirects,
+ /// A request or response asked for an invalid funcion.
+ Invalid,
#[doc(hidden)]
__DontMatchMe,
}
@@ -25,6 +27,7 @@ impl fmt::Display for Error {
Error::TooManyRedirects => {
f.pad("Too many redirects")
},
+ Error::Invalid => f.pad("Invalid operation"),
Error::__DontMatchMe => unreachable!()
}
}
@@ -36,6 +39,7 @@ impl StdError for Error {
Error::Http(ref e) => e.description(),
Error::Serialize(ref e) => e.description(),
Error::TooManyRedirects => "Too many redirects",
+ Error::Invalid => "Invalid operation",
Error::__DontMatchMe => unreachable!()
}
}
@@ -45,6 +49,7 @@ impl StdError for Error {
Error::Http(ref e) => Some(e),
Error::Serialize(ref e) => Some(&**e),
Error::TooManyRedirects => None,
+ Error::Invalid => None,
Error::__DontMatchMe => unreachable!()
}
}
@@ -68,5 +73,11 @@ impl From<::serde_urlencoded::ser::Error> for Error {
}
}
+impl From<::serde_json::Error> for Error {
+ fn from(err: ::serde_json::Error) -> Error {
+ Error::Serialize(Box::new(err))
+ }
+}
+
/// A `Result` alias where the `Err` case is `reqwest::Error`.
pub type Result<T> = ::std::result::Result<T, Error>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment