From ec049fefbae7355f6e4ddbbc7ebedcadb30e1e04 Mon Sep 17 00:00:00 2001 From: Garrett Squire Date: Tue, 28 Feb 2017 14:21:06 -0800 Subject: [PATCH] add a timeout option for read and write operations on a client --- src/client.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/client.rs b/src/client.rs index 5f40fcfda..d83145a0d 100644 --- a/src/client.rs +++ b/src/client.rs @@ -1,7 +1,8 @@ use std::fmt; use std::io::{self, Read}; -use std::sync::{Arc, Mutex}; +use std::sync::{Arc, Mutex, RwLock}; use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::Duration; use hyper::client::IntoUrl; 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); Ok(Client { inner: Arc::new(ClientRef { - hyper: client, + hyper: RwLock::new(client), redirect_policy: Mutex::new(RedirectPolicy::default()), auto_ungzip: AtomicBool::new(true), }), @@ -55,6 +56,13 @@ impl Client { *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. pub fn get(&self, url: U) -> RequestBuilder { self.request(Method::Get, url) @@ -113,7 +121,7 @@ impl fmt::Debug for Client { } struct ClientRef { - hyper: ::hyper::Client, + hyper: RwLock<::hyper::Client>, redirect_policy: Mutex, auto_ungzip: AtomicBool, } @@ -241,7 +249,8 @@ impl RequestBuilder { loop { let res = { 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()); if let Some(ref mut b) = body {