diff --git a/.travis.yml b/.travis.yml index 45b5740..a242db7 100644 --- a/.travis.yml +++ b/.travis.yml @@ -32,4 +32,4 @@ cache: script: - cargo build $FEATURES - - cargo test $FEATURES + - cargo test -v $FEATURES diff --git a/src/response.rs b/src/response.rs index 61394d4..a8f81e3 100644 --- a/src/response.rs +++ b/src/response.rs @@ -165,6 +165,32 @@ impl Response { serde_json::from_reader(self).map_err(::error::from) } + /// Copy the response body into a writer. + /// + /// This function internally uses [`std::io::copy`] and hence will continuously read data from + /// the body and then write it into writer in a streaming fashion until EOF is met. + /// + /// On success, the total number of bytes that were copied to `writer` is returned. + /// [`std::io::copy`]: https://doc.rust-lang.org/std/io/fn.copy.html + /// + /// # Example + /// + /// ```rust + /// # fn run() -> Result<(), Box<::std::error::Error>> { + /// let mut resp = reqwest::get("http://httpbin.org/range/5")?; + /// let mut buf: Vec = vec![]; + /// resp.copy_to(&mut buf)?; + /// assert_eq!(b"abcde", buf.as_slice()); + /// # Ok(()) + /// # } + /// ``` + #[inline] + pub fn copy_to(&mut self, w: &mut W) -> io::Result + where W: io::Write + { + io::copy(self, w) + } + /// Turn a response into an error if the server returned an error. /// /// # Example diff --git a/tests/client.rs b/tests/client.rs index bd4f6a8..541f1ba 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -5,6 +5,40 @@ mod support; use std::io::Read; +#[test] +fn test_response_copy_to() { + let server = server! { + request: b"\ + GET /1 HTTP/1.1\r\n\ + Host: $HOST\r\n\ + User-Agent: $USERAGENT\r\n\ + Accept: */*\r\n\ + Accept-Encoding: gzip\r\n\ + \r\n\ + ", + response: b"\ + HTTP/1.1 200 OK\r\n\ + Server: test\r\n\ + Content-Length: 5\r\n\ + \r\n\ + Hello\ + " + }; + + let url = format!("http://{}/1", server.addr()); + let mut res = reqwest::get(&url).unwrap(); + assert_eq!(res.url().as_str(), &url); + assert_eq!(res.status(), reqwest::StatusCode::Ok); + assert_eq!(res.headers().get(), + Some(&reqwest::header::Server::new("test".to_string()))); + assert_eq!(res.headers().get(), + Some(&reqwest::header::ContentLength(5))); + + let mut buf: Vec = vec![]; + res.copy_to(&mut buf).unwrap(); + assert_eq!(b"Hello", buf.as_slice()); +} + #[test] fn test_get() { let server = server! {