Skip to content

Commit

Permalink
add a timeout option for read and write operations on a client
Browse files Browse the repository at this point in the history
  • Loading branch information
gsquire authored and seanmonstar committed Mar 14, 2017
1 parent c929104 commit ec049fe
Showing 1 changed file with 13 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/client.rs
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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),
}),
Expand All @@ -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<U: IntoUrl>(&self, url: U) -> RequestBuilder {
self.request(Method::Get, url)
Expand Down Expand Up @@ -113,7 +121,7 @@ impl fmt::Debug for Client {
}

struct ClientRef {
hyper: ::hyper::Client,
hyper: RwLock<::hyper::Client>,
redirect_policy: Mutex<RedirectPolicy>,
auto_ungzip: AtomicBool,
}
Expand Down Expand Up @@ -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 {
Expand Down

0 comments on commit ec049fe

Please sign in to comment.