add a timeout option for read and write operations on a client

This commit is contained in:
Garrett Squire
2017-02-28 14:21:06 -08:00
committed by Sean McArthur
parent c9291049ee
commit ec049fefba

View File

@@ -1,7 +1,8 @@
use std::fmt; use std::fmt;
use std::io::{self, Read}; use std::io::{self, Read};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex, RwLock};
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
use hyper::client::IntoUrl; use hyper::client::IntoUrl;
use hyper::header::{Headers, ContentType, Location, Referer, UserAgent, Accept, ContentEncoding, Encoding, ContentLength, use hyper::header::{Headers, ContentType, Location, Referer, UserAgent, Accept, ContentEncoding, Encoding, ContentLength,
@@ -38,7 +39,7 @@ impl Client {
client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone); client.set_redirect_policy(::hyper::client::RedirectPolicy::FollowNone);
Ok(Client { Ok(Client {
inner: Arc::new(ClientRef { inner: Arc::new(ClientRef {
hyper: client, hyper: RwLock::new(client),
redirect_policy: Mutex::new(RedirectPolicy::default()), redirect_policy: Mutex::new(RedirectPolicy::default()),
auto_ungzip: AtomicBool::new(true), auto_ungzip: AtomicBool::new(true),
}), }),
@@ -55,6 +56,13 @@ impl Client {
*self.inner.redirect_policy.lock().unwrap() = policy; *self.inner.redirect_policy.lock().unwrap() = policy;
} }
/// Set a timeout for both the read and write operations of a client.
pub fn timeout(&mut self, timeout: Duration) {
let mut client = self.inner.hyper.write().unwrap();
client.set_read_timeout(Some(timeout));
client.set_write_timeout(Some(timeout));
}
/// Convenience method to make a `GET` request to a URL. /// Convenience method to make a `GET` request to a URL.
pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder { pub fn get<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::Get, url) self.request(Method::Get, url)
@@ -113,7 +121,7 @@ impl fmt::Debug for Client {
} }
struct ClientRef { struct ClientRef {
hyper: ::hyper::Client, hyper: RwLock<::hyper::Client>,
redirect_policy: Mutex<RedirectPolicy>, redirect_policy: Mutex<RedirectPolicy>,
auto_ungzip: AtomicBool, auto_ungzip: AtomicBool,
} }
@@ -241,7 +249,8 @@ impl RequestBuilder {
loop { loop {
let res = { let res = {
debug!("request {:?} \"{}\"", method, url); debug!("request {:?} \"{}\"", method, url);
let mut req = client.hyper.request(method.clone(), url.clone()) let c = client.hyper.read().unwrap();
let mut req = c.request(method.clone(), url.clone())
.headers(headers.clone()); .headers(headers.clone());
if let Some(ref mut b) = body { if let Some(ref mut b) = body {