Add request timeout (#761)

Closes #754
This commit is contained in:
kodieg
2020-01-03 20:25:04 +01:00
committed by Sean McArthur
parent c0f717cf30
commit b159963f6c
3 changed files with 65 additions and 9 deletions

View File

@@ -2,6 +2,7 @@ use std::convert::TryFrom;
use std::fmt;
use std::future::Future;
use std::io::Write;
use std::time::Duration;
use base64;
use base64::write::EncoderWriter as Base64Encoder;
@@ -23,6 +24,7 @@ pub struct Request {
url: Url,
headers: HeaderMap,
body: Option<Body>,
timeout: Option<Duration>,
}
/// A builder to construct the properties of a `Request`.
@@ -40,6 +42,7 @@ impl Request {
url,
headers: HeaderMap::new(),
body: None,
timeout: None
}
}
@@ -91,6 +94,18 @@ impl Request {
&mut self.body
}
/// Get the timeout.
#[inline]
pub fn timeout(&self) -> Option<&Duration> {
self.timeout.as_ref()
}
/// Get a mutable reference to the timeout.
#[inline]
pub fn timeout_mut(&mut self) -> &mut Option<Duration> {
&mut self.timeout
}
/// Attempt to clone the request.
///
/// `None` is returned if the request can not be cloned, i.e. if the body is a stream.
@@ -100,13 +115,14 @@ impl Request {
None => None,
};
let mut req = Request::new(self.method().clone(), self.url().clone());
*req.timeout_mut() = self.timeout().cloned();
*req.headers_mut() = self.headers().clone();
req.body = body;
Some(req)
}
pub(super) fn pieces(self) -> (Method, Url, HeaderMap, Option<Body>) {
(self.method, self.url, self.headers, self.body)
pub(super) fn pieces(self) -> (Method, Url, HeaderMap, Option<Body>, Option<Duration>) {
(self.method, self.url, self.headers, self.body, self.timeout)
}
}
@@ -199,6 +215,18 @@ impl RequestBuilder {
self
}
/// Enables a request timeout.
///
/// The timeout is applied from the when the request starts connecting
/// until the response body has finished. It affects only this request
/// and overrides the timeout configured using `ClientBuilder::timeout()`.
pub fn timeout(mut self, timeout: Duration) -> RequestBuilder {
if let Ok(ref mut req) = self.request {
*req.timeout_mut() = Some(timeout);
}
self
}
/// Sends a multipart/form-data body.
///
/// ```