use std::fmt;
use base64::encode;
use serde::Serialize;
use serde_json;
use serde_urlencoded;
use body::{self, Body};
use header::{HeaderMap, HeaderName, HeaderValue, CONTENT_TYPE};
use http::HttpTryFrom;
use {async_impl, Client, Method, Url};
pub struct Request {
body: Option<Body>,
inner: async_impl::Request,
}
#[derive(Debug)]
pub struct RequestBuilder {
client: Client,
request: ::Result<Request>,
}
impl Request {
#[inline]
pub fn new(method: Method, url: Url) -> Self {
Request {
body: None,
inner: async_impl::Request::new(method, url),
}
}
#[inline]
pub fn method(&self) -> &Method {
self.inner.method()
}
#[inline]
pub fn method_mut(&mut self) -> &mut Method {
self.inner.method_mut()
}
#[inline]
pub fn url(&self) -> &Url {
self.inner.url()
}
#[inline]
pub fn url_mut(&mut self) -> &mut Url {
self.inner.url_mut()
}
#[inline]
pub fn headers(&self) -> &HeaderMap {
self.inner.headers()
}
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.inner.headers_mut()
}
#[inline]
pub fn body(&self) -> Option<&Body> {
self.body.as_ref()
}
#[inline]
pub fn body_mut(&mut self) -> &mut Option<Body> {
&mut self.body
}
pub fn try_clone(&self) -> Option<Request> {
let body = if let Some(ref body) = self.body.as_ref() {
if let Some(body) = body.try_clone() {
Some(body)
} else {
return None;
}
} else {
None
};
let mut req = Request::new(self.method().clone(), self.url().clone());
*req.headers_mut() = self.headers().clone();
req.body = body;
Some(req)
}
pub(crate) fn into_async(self) -> (async_impl::Request, Option<body::Sender>) {
use header::CONTENT_LENGTH;
let mut req_async = self.inner;
let body = self.body.and_then(|body| {
let (tx, body, len) = body.into_async();
if let Some(len) = len {
req_async.headers_mut().insert(CONTENT_LENGTH, len.into());
}
*req_async.body_mut() = Some(body);
tx
});
(req_async, body)
}
}
impl RequestBuilder {
pub(crate) fn new(client: Client, request: ::Result<Request>) -> RequestBuilder {
RequestBuilder {
client,
request,
}
}
pub fn header<K, V>(mut self, key: K, value: V) -> RequestBuilder
where
HeaderName: HttpTryFrom<K>,
HeaderValue: HttpTryFrom<V>,
{
let mut error = None;
if let Ok(ref mut req) = self.request {
match <HeaderName as HttpTryFrom<K>>::try_from(key) {
Ok(key) => {
match <HeaderValue as HttpTryFrom<V>>::try_from(value) {
Ok(value) => { req.headers_mut().append(key, value); }
Err(e) => error = Some(::error::from(e.into())),
}
},
Err(e) => error = Some(::error::from(e.into())),
};
}
if let Some(err) = error {
self.request = Err(err);
}
self
}
pub fn headers(mut self, headers: ::header::HeaderMap) -> RequestBuilder {
if let Ok(ref mut req) = self.request {
async_impl::request::replace_headers(req.headers_mut(), headers);
}
self
}
#[cfg(feature = "hyper-011")]
pub fn header_011<H>(self, header: H) -> RequestBuilder
where
H: ::hyper_011::header::Header,
{
let mut headers = ::hyper_011::Headers::new();
headers.set(header);
let map = ::header::HeaderMap::from(headers);
self.headers(map)
}
#[cfg(feature = "hyper-011")]
pub fn headers_011(self, headers: ::hyper_011::Headers) -> RequestBuilder {
let map = ::header::HeaderMap::from(headers);
self.headers(map)
}
pub fn basic_auth<U, P>(self, username: U, password: Option<P>) -> RequestBuilder
where
U: fmt::Display,
P: fmt::Display,
{
let auth = match password {
Some(password) => format!("{}:{}", username, password),
None => format!("{}:", username)
};
let header_value = format!("Basic {}", encode(&auth));
self.header(::header::AUTHORIZATION, &*header_value)
}
pub fn bearer_auth<T>(self, token: T) -> RequestBuilder
where
T: fmt::Display,
{
let header_value = format!("Bearer {}", token);
self.header(::header::AUTHORIZATION, &*header_value)
}
pub fn body<T: Into<Body>>(mut self, body: T) -> RequestBuilder {
if let Ok(ref mut req) = self.request {
*req.body_mut() = Some(body.into());
}
self
}
pub fn query<T: Serialize + ?Sized>(mut self, query: &T) -> RequestBuilder {
let mut error = None;
if let Ok(ref mut req) = self.request {
let url = req.url_mut();
let mut pairs = url.query_pairs_mut();
let serializer = serde_urlencoded::Serializer::new(&mut pairs);
if let Err(err) = query.serialize(serializer) {
error = Some(::error::from(err));
}
}
if let Ok(ref mut req) = self.request {
if let Some("") = req.url().query() {
req.url_mut().set_query(None);
}
}
if let Some(err) = error {
self.request = Err(err);
}
self
}
pub fn form<T: Serialize + ?Sized>(mut self, form: &T) -> RequestBuilder {
let mut error = None;
if let Ok(ref mut req) = self.request {
match serde_urlencoded::to_string(form) {
Ok(body) => {
req.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/x-www-form-urlencoded")
);
*req.body_mut() = Some(body.into());
},
Err(err) => error = Some(::error::from(err)),
}
}
if let Some(err) = error {
self.request = Err(err);
}
self
}
pub fn json<T: Serialize + ?Sized>(mut self, json: &T) -> RequestBuilder {
let mut error = None;
if let Ok(ref mut req) = self.request {
match serde_json::to_vec(json) {
Ok(body) => {
req.headers_mut().insert(
CONTENT_TYPE,
HeaderValue::from_static("application/json")
);
*req.body_mut() = Some(body.into());
},
Err(err) => error = Some(::error::from(err)),
}
}
if let Some(err) = error {
self.request = Err(err);
}
self
}
pub fn multipart(self, mut multipart: ::multipart::Form) -> RequestBuilder {
let mut builder = self.header(
CONTENT_TYPE,
format!(
"multipart/form-data; boundary={}",
multipart.boundary()
).as_str()
);
if let Ok(ref mut req) = builder.request {
*req.body_mut() = Some(match multipart.compute_length() {
Some(length) => Body::sized(multipart.reader(), length),
None => Body::new(multipart.reader()),
})
}
builder
}
pub fn build(self) -> ::Result<Request> {
self.request
}
pub fn send(self) -> ::Result<::Response> {
self.client.execute(self.request?)
}
pub fn try_clone(&self) -> Option<RequestBuilder> {
self.request.as_ref()
.ok()
.and_then(|req| req.try_clone())
.map(|req| {
RequestBuilder{
client: self.client.clone(),
request: Ok(req),
}
})
}
}
impl fmt::Debug for Request {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
fmt_request_fields(&mut f.debug_struct("Request"), self)
.finish()
}
}
fn fmt_request_fields<'a, 'b>(f: &'a mut fmt::DebugStruct<'a, 'b>, req: &Request) -> &'a mut fmt::DebugStruct<'a, 'b> {
f.field("method", req.method())
.field("url", req.url())
.field("headers", req.headers())
}
#[cfg(test)]
mod tests {
use {body, Client, Method};
use header::{ACCEPT, HOST, HeaderMap, HeaderValue, CONTENT_TYPE};
use std::collections::{BTreeMap, HashMap};
use serde::Serialize;
use serde_json;
use serde_urlencoded;
#[test]
fn basic_get_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.get(some_url).build().unwrap();
assert_eq!(r.method(), &Method::GET);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn basic_head_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.head(some_url).build().unwrap();
assert_eq!(r.method(), &Method::HEAD);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn basic_post_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url).build().unwrap();
assert_eq!(r.method(), &Method::POST);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn basic_put_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.put(some_url).build().unwrap();
assert_eq!(r.method(), &Method::PUT);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn basic_patch_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.patch(some_url).build().unwrap();
assert_eq!(r.method(), &Method::PATCH);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn basic_delete_request() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.delete(some_url).build().unwrap();
assert_eq!(r.method(), &Method::DELETE);
assert_eq!(r.url().as_str(), some_url);
}
#[test]
fn add_header() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let header = HeaderValue::from_static("google.com");
let r = r.header(HOST, header.clone()).build().unwrap();
assert_eq!(r.headers().get(HOST), Some(&header));
}
#[test]
fn add_headers() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let header = HeaderValue::from_static("google.com");
let mut headers = HeaderMap::new();
headers.insert(HOST, header);
let r = r.headers(headers.clone()).build().unwrap();
assert_eq!(r.headers(), &headers);
}
#[test]
fn add_headers_multi() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let header_json = HeaderValue::from_static("application/json");
let header_xml = HeaderValue::from_static("application/xml");
let mut headers = HeaderMap::new();
headers.append(ACCEPT, header_json);
headers.append(ACCEPT, header_xml);
let r = r.headers(headers.clone()).build().unwrap();
assert_eq!(r.headers(), &headers);
let mut all_values = r.headers().get_all(ACCEPT).iter();
assert_eq!(all_values.next().unwrap(), &"application/json");
assert_eq!(all_values.next().unwrap(), &"application/xml");
assert_eq!(all_values.next(), None);
}
#[test]
fn add_body() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let body = "Some interesting content";
let mut r = r.body(body).build().unwrap();
let buf = body::read_to_string(r.body_mut().take().unwrap()).unwrap();
assert_eq!(buf, body);
}
#[test]
fn add_query_append() {
let client = Client::new();
let some_url = "https://google.com/";
let mut r = client.get(some_url);
r = r.query(&[("foo", "bar")]);
r = r.query(&[("qux", 3)]);
let req = r.build().expect("request is valid");
assert_eq!(req.url().query(), Some("foo=bar&qux=3"));
}
#[test]
fn add_query_append_same() {
let client = Client::new();
let some_url = "https://google.com/";
let mut r = client.get(some_url);
r = r.query(&[("foo", "a"), ("foo", "b")]);
let req = r.build().expect("request is valid");
assert_eq!(req.url().query(), Some("foo=a&foo=b"));
}
#[test]
fn add_query_struct() {
#[derive(Serialize)]
struct Params {
foo: String,
qux: i32,
}
let client = Client::new();
let some_url = "https://google.com/";
let mut r = client.get(some_url);
let params = Params { foo: "bar".into(), qux: 3 };
r = r.query(¶ms);
let req = r.build().expect("request is valid");
assert_eq!(req.url().query(), Some("foo=bar&qux=3"));
}
#[test]
fn add_query_map() {
let mut params = BTreeMap::new();
params.insert("foo", "bar");
params.insert("qux", "three");
let client = Client::new();
let some_url = "https://google.com/";
let mut r = client.get(some_url);
r = r.query(¶ms);
let req = r.build().expect("request is valid");
assert_eq!(req.url().query(), Some("foo=bar&qux=three"));
}
#[test]
fn add_form() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let mut form_data = HashMap::new();
form_data.insert("foo", "bar");
let mut r = r.form(&form_data).build().unwrap();
assert_eq!(r.headers().get(CONTENT_TYPE).unwrap(), &"application/x-www-form-urlencoded");
let buf = body::read_to_string(r.body_mut().take().unwrap()).unwrap();
let body_should_be = serde_urlencoded::to_string(&form_data).unwrap();
assert_eq!(buf, body_should_be);
}
#[test]
fn add_json() {
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let mut json_data = HashMap::new();
json_data.insert("foo", "bar");
let mut r = r.json(&json_data).build().unwrap();
assert_eq!(r.headers().get(CONTENT_TYPE).unwrap(), &"application/json");
let buf = body::read_to_string(r.body_mut().take().unwrap()).unwrap();
let body_should_be = serde_json::to_string(&json_data).unwrap();
assert_eq!(buf, body_should_be);
}
#[test]
fn add_json_fail() {
use serde::{Serialize, Serializer};
use serde::ser::Error;
struct MyStruct;
impl Serialize for MyStruct {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
Err(S::Error::custom("nope"))
}
}
let client = Client::new();
let some_url = "https://google.com/";
let r = client.post(some_url);
let json_data = MyStruct;
assert!(r.json(&json_data).build().unwrap_err().is_serialization());
}
#[test]
fn test_replace_headers() {
use http::HeaderMap;
let mut headers = HeaderMap::new();
headers.insert("foo", "bar".parse().unwrap());
headers.append("foo", "baz".parse().unwrap());
let client = Client::new();
let req = client
.get("https://hyper.rs")
.header("im-a", "keeper")
.header("foo", "pop me")
.headers(headers)
.build()
.expect("request build");
assert_eq!(req.headers()["im-a"], "keeper");
let foo = req
.headers()
.get_all("foo")
.iter()
.collect::<Vec<_>>();
assert_eq!(foo.len(), 2);
assert_eq!(foo[0], "bar");
assert_eq!(foo[1], "baz");
}
#[test]
fn normalize_empty_query() {
let client = Client::new();
let some_url = "https://google.com/";
let empty_query: &[(&str, &str)] = &[];
let req = client
.get(some_url)
.query(empty_query)
.build()
.expect("request build");
assert_eq!(req.url().query(), None);
assert_eq!(req.url().as_str(), "https://google.com/");
}
}