2017-11-16 07:06:28 +01:00
|
|
|
//! Pieces pertaining to the HTTP response.
|
2017-12-04 05:09:46 +01:00
|
|
|
use std::{mem, str, fmt};
|
2017-10-07 06:48:14 +02:00
|
|
|
use std::convert::Into;
|
|
|
|
|
2017-10-14 19:40:58 +02:00
|
|
|
use cookie::CookieJar;
|
2017-11-28 22:52:53 +01:00
|
|
|
use bytes::{Bytes, BytesMut};
|
2017-10-22 18:13:29 +02:00
|
|
|
use http::{StatusCode, Version, HeaderMap, HttpTryFrom, Error as HttpError};
|
2017-10-10 08:07:32 +02:00
|
|
|
use http::header::{self, HeaderName, HeaderValue};
|
2017-11-27 19:39:47 +01:00
|
|
|
use serde_json;
|
|
|
|
use serde::Serialize;
|
2017-12-08 01:40:29 +01:00
|
|
|
use cookie::Cookie;
|
|
|
|
|
2017-10-24 08:25:32 +02:00
|
|
|
use body::Body;
|
2017-11-25 18:03:44 +01:00
|
|
|
use error::Error;
|
2017-12-04 23:53:40 +01:00
|
|
|
use handler::FromRequest;
|
2017-11-07 01:23:58 +01:00
|
|
|
use encoding::ContentEncoding;
|
2017-12-03 02:14:55 +01:00
|
|
|
use httprequest::HttpRequest;
|
2017-10-15 07:52:38 +02:00
|
|
|
|
|
|
|
/// Represents various types of connection
|
2017-10-08 06:48:00 +02:00
|
|
|
#[derive(Copy, Clone, PartialEq, Debug)]
|
|
|
|
pub enum ConnectionType {
|
2017-10-15 07:52:38 +02:00
|
|
|
/// Close connection after response
|
2017-10-08 06:48:00 +02:00
|
|
|
Close,
|
2017-10-15 07:52:38 +02:00
|
|
|
/// Keep connection alive after response
|
2017-10-08 06:48:00 +02:00
|
|
|
KeepAlive,
|
2017-10-15 07:52:38 +02:00
|
|
|
/// Connection is upgraded to different type
|
2017-10-08 06:48:00 +02:00
|
|
|
Upgrade,
|
|
|
|
}
|
|
|
|
|
2017-10-07 06:48:14 +02:00
|
|
|
/// An HTTP Response
|
2017-10-07 08:14:13 +02:00
|
|
|
pub struct HttpResponse {
|
2017-12-08 02:38:18 +01:00
|
|
|
version: Option<Version>,
|
|
|
|
headers: HeaderMap,
|
|
|
|
status: StatusCode,
|
2017-10-08 06:48:00 +02:00
|
|
|
reason: Option<&'static str>,
|
2017-10-07 06:48:14 +02:00
|
|
|
body: Body,
|
|
|
|
chunked: bool,
|
2017-11-06 10:24:49 +01:00
|
|
|
encoding: ContentEncoding,
|
2017-10-08 06:48:00 +02:00
|
|
|
connection_type: Option<ConnectionType>,
|
2017-11-10 21:29:54 +01:00
|
|
|
response_size: u64,
|
2017-11-25 18:03:44 +01:00
|
|
|
error: Option<Error>,
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-10-07 08:14:13 +02:00
|
|
|
impl HttpResponse {
|
2017-10-11 01:03:32 +02:00
|
|
|
|
2017-11-27 07:31:29 +01:00
|
|
|
/// Create http response builder with specific status.
|
2017-10-11 01:03:32 +02:00
|
|
|
#[inline]
|
2017-11-27 07:31:29 +01:00
|
|
|
pub fn build(status: StatusCode) -> HttpResponseBuilder {
|
2017-10-15 23:17:41 +02:00
|
|
|
HttpResponseBuilder {
|
2017-10-11 01:03:32 +02:00
|
|
|
parts: Some(Parts::new(status)),
|
|
|
|
err: None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-07 08:14:13 +02:00
|
|
|
/// Constructs a response
|
2017-10-07 06:48:14 +02:00
|
|
|
#[inline]
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn new(status: StatusCode, body: Body) -> HttpResponse {
|
2017-10-07 08:14:13 +02:00
|
|
|
HttpResponse {
|
2017-10-11 02:14:30 +02:00
|
|
|
version: None,
|
2017-10-07 06:48:14 +02:00
|
|
|
headers: Default::default(),
|
|
|
|
status: status,
|
2017-10-08 06:48:00 +02:00
|
|
|
reason: None,
|
2017-10-07 06:48:14 +02:00
|
|
|
body: body,
|
|
|
|
chunked: false,
|
2017-11-06 10:24:49 +01:00
|
|
|
encoding: ContentEncoding::Auto,
|
2017-10-08 06:48:00 +02:00
|
|
|
connection_type: None,
|
2017-11-10 21:29:54 +01:00
|
|
|
response_size: 0,
|
2017-11-25 18:03:44 +01:00
|
|
|
error: None,
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-25 18:03:44 +01:00
|
|
|
/// Constructs a error response
|
|
|
|
#[inline]
|
|
|
|
pub fn from_error(error: Error) -> HttpResponse {
|
|
|
|
let mut resp = error.cause().error_response();
|
|
|
|
resp.error = Some(error);
|
|
|
|
resp
|
|
|
|
}
|
|
|
|
|
|
|
|
/// The source `error` for this response
|
|
|
|
#[inline]
|
|
|
|
pub fn error(&self) -> Option<&Error> {
|
|
|
|
self.error.as_ref()
|
|
|
|
}
|
|
|
|
|
2017-10-07 06:48:14 +02:00
|
|
|
/// Get the HTTP version of this response.
|
|
|
|
#[inline]
|
2017-10-11 02:14:30 +02:00
|
|
|
pub fn version(&self) -> Option<Version> {
|
2017-10-07 06:48:14 +02:00
|
|
|
self.version
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the headers from the response.
|
|
|
|
#[inline]
|
2017-10-10 08:07:32 +02:00
|
|
|
pub fn headers(&self) -> &HeaderMap {
|
2017-10-07 06:48:14 +02:00
|
|
|
&self.headers
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get a mutable reference to the headers.
|
|
|
|
#[inline]
|
2017-10-10 08:07:32 +02:00
|
|
|
pub fn headers_mut(&mut self) -> &mut HeaderMap {
|
2017-10-07 06:48:14 +02:00
|
|
|
&mut self.headers
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Get the status from the server.
|
|
|
|
#[inline]
|
|
|
|
pub fn status(&self) -> StatusCode {
|
|
|
|
self.status
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the `StatusCode` for this response.
|
|
|
|
#[inline]
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn status_mut(&mut self) -> &mut StatusCode {
|
|
|
|
&mut self.status
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-10-14 19:01:53 +02:00
|
|
|
/// Get custom reason for the response.
|
|
|
|
#[inline]
|
|
|
|
pub fn reason(&self) -> &str {
|
2017-10-16 10:19:23 +02:00
|
|
|
if let Some(reason) = self.reason {
|
2017-10-14 19:01:53 +02:00
|
|
|
reason
|
|
|
|
} else {
|
|
|
|
""
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-08 06:48:00 +02:00
|
|
|
/// Set the custom reason for the response.
|
|
|
|
#[inline]
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn set_reason(&mut self, reason: &'static str) -> &mut Self {
|
2017-10-08 06:48:00 +02:00
|
|
|
self.reason = Some(reason);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set connection type
|
2017-10-14 19:01:53 +02:00
|
|
|
pub fn set_connection_type(&mut self, conn: ConnectionType) -> &mut Self {
|
2017-10-08 06:48:00 +02:00
|
|
|
self.connection_type = Some(conn);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Connection upgrade status
|
|
|
|
pub fn upgrade(&self) -> bool {
|
|
|
|
self.connection_type == Some(ConnectionType::Upgrade)
|
|
|
|
}
|
|
|
|
|
2017-10-07 06:48:14 +02:00
|
|
|
/// Keep-alive status for this connection
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn keep_alive(&self) -> Option<bool> {
|
2017-10-23 07:54:11 +02:00
|
|
|
if let Some(ct) = self.connection_type {
|
|
|
|
match ct {
|
|
|
|
ConnectionType::KeepAlive => Some(true),
|
|
|
|
ConnectionType::Close | ConnectionType::Upgrade => Some(false),
|
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
} else {
|
2017-10-11 01:03:32 +02:00
|
|
|
None
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
}
|
2017-10-08 06:48:00 +02:00
|
|
|
|
2017-10-07 06:48:14 +02:00
|
|
|
/// is chunked encoding enabled
|
|
|
|
pub fn chunked(&self) -> bool {
|
|
|
|
self.chunked
|
|
|
|
}
|
|
|
|
|
2017-11-06 23:56:38 +01:00
|
|
|
/// Content encoding
|
|
|
|
pub fn content_encoding(&self) -> &ContentEncoding {
|
|
|
|
&self.encoding
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set content encoding
|
|
|
|
pub fn set_content_encoding(&mut self, enc: ContentEncoding) -> &mut Self {
|
|
|
|
self.encoding = enc;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-10-07 08:14:13 +02:00
|
|
|
/// Get body os this response
|
2017-10-07 06:48:14 +02:00
|
|
|
pub fn body(&self) -> &Body {
|
|
|
|
&self.body
|
|
|
|
}
|
|
|
|
|
2017-10-08 06:48:00 +02:00
|
|
|
/// Set a body
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn set_body<B: Into<Body>>(&mut self, body: B) {
|
2017-10-08 06:48:00 +02:00
|
|
|
self.body = body.into();
|
|
|
|
}
|
|
|
|
|
2017-10-07 08:14:13 +02:00
|
|
|
/// Set a body and return previous body value
|
2017-10-08 06:48:00 +02:00
|
|
|
pub fn replace_body<B: Into<Body>>(&mut self, body: B) -> Body {
|
2017-10-07 06:48:14 +02:00
|
|
|
mem::replace(&mut self.body, body.into())
|
|
|
|
}
|
2017-11-10 21:29:54 +01:00
|
|
|
|
|
|
|
/// Size of response in bytes, excluding HTTP headers
|
|
|
|
pub fn response_size(&self) -> u64 {
|
|
|
|
self.response_size
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set content encoding
|
|
|
|
pub(crate) fn set_response_size(&mut self, size: u64) {
|
|
|
|
self.response_size = size;
|
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
2017-10-11 01:03:32 +02:00
|
|
|
|
2017-11-09 04:31:25 +01:00
|
|
|
impl fmt::Debug for HttpResponse {
|
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
let res = write!(f, "\nHttpResponse {:?} {}{}\n",
|
|
|
|
self.version, self.status, self.reason.unwrap_or(""));
|
|
|
|
let _ = write!(f, " encoding: {:?}\n", self.encoding);
|
|
|
|
let _ = write!(f, " headers:\n");
|
|
|
|
for key in self.headers.keys() {
|
|
|
|
let vals: Vec<_> = self.headers.get_all(key).iter().collect();
|
|
|
|
if vals.len() > 1 {
|
|
|
|
let _ = write!(f, " {:?}: {:?}\n", key, vals);
|
|
|
|
} else {
|
|
|
|
let _ = write!(f, " {:?}: {:?}\n", key, vals[0]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
res
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-11 01:03:32 +02:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct Parts {
|
2017-10-11 02:14:30 +02:00
|
|
|
version: Option<Version>,
|
2017-10-11 01:03:32 +02:00
|
|
|
headers: HeaderMap,
|
|
|
|
status: StatusCode,
|
|
|
|
reason: Option<&'static str>,
|
|
|
|
chunked: bool,
|
2017-11-06 10:24:49 +01:00
|
|
|
encoding: ContentEncoding,
|
2017-10-11 01:03:32 +02:00
|
|
|
connection_type: Option<ConnectionType>,
|
2017-10-14 19:40:58 +02:00
|
|
|
cookies: CookieJar,
|
2017-10-11 01:03:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl Parts {
|
|
|
|
fn new(status: StatusCode) -> Self {
|
|
|
|
Parts {
|
2017-10-11 02:14:30 +02:00
|
|
|
version: None,
|
2017-10-11 01:03:32 +02:00
|
|
|
headers: HeaderMap::new(),
|
|
|
|
status: status,
|
|
|
|
reason: None,
|
|
|
|
chunked: false,
|
2017-11-06 10:24:49 +01:00
|
|
|
encoding: ContentEncoding::Auto,
|
2017-10-11 01:03:32 +02:00
|
|
|
connection_type: None,
|
2017-10-14 19:40:58 +02:00
|
|
|
cookies: CookieJar::new(),
|
2017-10-11 01:03:32 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/// An HTTP response builder
|
|
|
|
///
|
|
|
|
/// This type can be used to construct an instance of `HttpResponse` through a
|
|
|
|
/// builder-like pattern.
|
|
|
|
#[derive(Debug)]
|
2017-10-15 23:17:41 +02:00
|
|
|
pub struct HttpResponseBuilder {
|
2017-10-11 01:03:32 +02:00
|
|
|
parts: Option<Parts>,
|
2017-10-22 18:13:29 +02:00
|
|
|
err: Option<HttpError>,
|
2017-10-11 01:03:32 +02:00
|
|
|
}
|
|
|
|
|
2017-10-15 23:17:41 +02:00
|
|
|
impl HttpResponseBuilder {
|
2017-11-28 23:29:22 +01:00
|
|
|
/// Set the HTTP version of this response.
|
2017-10-11 01:03:32 +02:00
|
|
|
#[inline]
|
|
|
|
pub fn version(&mut self, version: Version) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
2017-10-11 02:14:30 +02:00
|
|
|
parts.version = Some(version);
|
2017-10-11 01:03:32 +02:00
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the `StatusCode` for this response.
|
|
|
|
#[inline]
|
|
|
|
pub fn status(&mut self, status: StatusCode) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.status = status;
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set a header.
|
|
|
|
#[inline]
|
|
|
|
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
|
|
|
|
where HeaderName: HttpTryFrom<K>,
|
|
|
|
HeaderValue: HttpTryFrom<V>
|
|
|
|
{
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
match HeaderName::try_from(key) {
|
|
|
|
Ok(key) => {
|
|
|
|
match HeaderValue::try_from(value) {
|
|
|
|
Ok(value) => { parts.headers.append(key, value); }
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set the custom reason for the response.
|
|
|
|
#[inline]
|
|
|
|
pub fn reason(&mut self, reason: &'static str) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.reason = Some(reason);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-11-06 10:24:49 +01:00
|
|
|
/// Set content encoding.
|
|
|
|
///
|
|
|
|
/// By default `ContentEncoding::Auto` is used, which automatically
|
2017-11-06 23:56:38 +01:00
|
|
|
/// negotiates content encoding based on request's `Accept-Encoding` headers.
|
2017-11-30 16:42:02 +01:00
|
|
|
/// To enforce specific encoding, use specific ContentEncoding` value.
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-11-06 10:24:49 +01:00
|
|
|
pub fn content_encoding(&mut self, enc: ContentEncoding) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.encoding = enc;
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-10-11 01:03:32 +02:00
|
|
|
/// Set connection type
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-10-14 19:01:53 +02:00
|
|
|
pub fn connection_type(&mut self, conn: ConnectionType) -> &mut Self {
|
2017-10-11 01:03:32 +02:00
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.connection_type = Some(conn);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-10-14 19:01:53 +02:00
|
|
|
/// Set connection type to Upgrade
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-10-14 19:01:53 +02:00
|
|
|
pub fn upgrade(&mut self) -> &mut Self {
|
|
|
|
self.connection_type(ConnectionType::Upgrade)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Force close connection, even if it is marked as keep-alive
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-10-14 19:01:53 +02:00
|
|
|
pub fn force_close(&mut self) -> &mut Self {
|
|
|
|
self.connection_type(ConnectionType::Close)
|
|
|
|
}
|
|
|
|
|
2017-10-11 01:03:32 +02:00
|
|
|
/// Enables automatic chunked transfer encoding
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-10-11 01:03:32 +02:00
|
|
|
pub fn enable_chunked(&mut self) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.chunked = true;
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-10-14 19:01:53 +02:00
|
|
|
/// Set response content type
|
2017-12-04 05:47:15 +01:00
|
|
|
#[inline]
|
2017-10-14 19:01:53 +02:00
|
|
|
pub fn content_type<V>(&mut self, value: V) -> &mut Self
|
|
|
|
where HeaderValue: HttpTryFrom<V>
|
|
|
|
{
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
match HeaderValue::try_from(value) {
|
|
|
|
Ok(value) => { parts.headers.insert(header::CONTENT_TYPE, value); },
|
|
|
|
Err(e) => self.err = Some(e.into()),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-10-14 19:40:58 +02:00
|
|
|
/// Set a cookie
|
|
|
|
pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.cookies.add(cookie.into_owned());
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Remote cookie, cookie has to be cookie from `HttpRequest::cookies()` method.
|
|
|
|
pub fn del_cookie<'a>(&mut self, cookie: &Cookie<'a>) -> &mut Self {
|
|
|
|
if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
let cookie = cookie.clone().into_owned();
|
|
|
|
parts.cookies.add_original(cookie.clone());
|
|
|
|
parts.cookies.remove(cookie);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-05 05:38:38 +01:00
|
|
|
/// Calls provided closure with builder reference if value is true.
|
2017-10-29 22:51:02 +01:00
|
|
|
pub fn if_true<F>(&mut self, value: bool, f: F) -> &mut Self
|
|
|
|
where F: Fn(&mut HttpResponseBuilder) + 'static
|
|
|
|
{
|
|
|
|
if value {
|
|
|
|
f(self);
|
|
|
|
}
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-11-27 19:39:47 +01:00
|
|
|
/// Set a body and generate `HttpResponse`.
|
|
|
|
/// `HttpResponseBuilder` can not be used after this call.
|
2017-10-22 18:13:29 +02:00
|
|
|
pub fn body<B: Into<Body>>(&mut self, body: B) -> Result<HttpResponse, HttpError> {
|
2017-10-14 19:40:58 +02:00
|
|
|
let mut parts = self.parts.take().expect("cannot reuse response builder");
|
2017-10-11 01:03:32 +02:00
|
|
|
if let Some(e) = self.err.take() {
|
|
|
|
return Err(e)
|
|
|
|
}
|
2017-10-14 19:40:58 +02:00
|
|
|
for cookie in parts.cookies.delta() {
|
|
|
|
parts.headers.append(
|
|
|
|
header::SET_COOKIE,
|
|
|
|
HeaderValue::from_str(&cookie.to_string())?);
|
|
|
|
}
|
2017-10-11 01:03:32 +02:00
|
|
|
Ok(HttpResponse {
|
|
|
|
version: parts.version,
|
|
|
|
headers: parts.headers,
|
|
|
|
status: parts.status,
|
|
|
|
reason: parts.reason,
|
|
|
|
body: body.into(),
|
|
|
|
chunked: parts.chunked,
|
2017-11-06 10:24:49 +01:00
|
|
|
encoding: parts.encoding,
|
2017-10-11 01:03:32 +02:00
|
|
|
connection_type: parts.connection_type,
|
2017-11-10 21:29:54 +01:00
|
|
|
response_size: 0,
|
2017-11-25 18:03:44 +01:00
|
|
|
error: None,
|
2017-10-11 01:03:32 +02:00
|
|
|
})
|
|
|
|
}
|
2017-10-24 08:52:20 +02:00
|
|
|
|
2017-11-27 19:39:47 +01:00
|
|
|
/// Set a json body and generate `HttpResponse`
|
|
|
|
pub fn json<T: Serialize>(&mut self, value: T) -> Result<HttpResponse, Error> {
|
|
|
|
let body = serde_json::to_string(&value)?;
|
|
|
|
|
|
|
|
let contains = if let Some(parts) = parts(&mut self.parts, &self.err) {
|
|
|
|
parts.headers.contains_key(header::CONTENT_TYPE)
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
};
|
|
|
|
if !contains {
|
|
|
|
self.header(header::CONTENT_TYPE, "application/json");
|
|
|
|
}
|
|
|
|
|
|
|
|
Ok(self.body(body)?)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set an empty body and generate `HttpResponse`
|
2017-10-24 08:52:20 +02:00
|
|
|
pub fn finish(&mut self) -> Result<HttpResponse, HttpError> {
|
|
|
|
self.body(Body::Empty)
|
|
|
|
}
|
2017-10-11 01:03:32 +02:00
|
|
|
}
|
|
|
|
|
2017-10-22 18:13:29 +02:00
|
|
|
fn parts<'a>(parts: &'a mut Option<Parts>, err: &Option<HttpError>) -> Option<&'a mut Parts>
|
2017-10-11 01:03:32 +02:00
|
|
|
{
|
|
|
|
if err.is_some() {
|
|
|
|
return None
|
|
|
|
}
|
|
|
|
parts.as_mut()
|
|
|
|
}
|
2017-10-23 07:54:11 +02:00
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
/// Helper converters
|
|
|
|
impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse {
|
|
|
|
fn from(res: Result<I, E>) -> Self {
|
|
|
|
match res {
|
|
|
|
Ok(val) => val.into(),
|
|
|
|
Err(err) => err.into().into(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-29 18:17:00 +01:00
|
|
|
impl From<HttpResponseBuilder> for HttpResponse {
|
|
|
|
fn from(mut builder: HttpResponseBuilder) -> Self {
|
|
|
|
builder.finish().into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for HttpResponseBuilder {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(mut self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
|
|
|
self.finish()
|
2017-12-03 02:14:55 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl From<&'static str> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: &'static str) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for &'static str {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl From<&'static [u8]> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: &'static [u8]) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for &'static [u8] {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl From<String> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: String) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for String {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl<'a> From<&'a String> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: &'a String) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl<'a> FromRequest for &'a String {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("text/plain; charset=utf-8")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl From<Bytes> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: Bytes) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for Bytes {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
impl From<BytesMut> for HttpResponse {
|
2017-11-29 18:17:00 +01:00
|
|
|
fn from(val: BytesMut) -> Self {
|
2017-11-28 22:52:53 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(val)
|
|
|
|
.into()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-03 02:14:55 +01:00
|
|
|
impl FromRequest for BytesMut {
|
2017-12-03 23:22:04 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = HttpError;
|
|
|
|
|
|
|
|
fn from_request(self, _: HttpRequest) -> Result<HttpResponse, HttpError> {
|
2017-12-03 02:14:55 +01:00
|
|
|
HttpResponse::build(StatusCode::OK)
|
|
|
|
.content_type("application/octet-stream")
|
|
|
|
.body(self)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-23 07:54:11 +02:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2017-11-28 22:52:53 +01:00
|
|
|
use body::Binary;
|
2017-10-23 07:54:11 +02:00
|
|
|
|
2017-11-28 23:29:22 +01:00
|
|
|
#[test]
|
|
|
|
fn test_basic_builder() {
|
|
|
|
let resp = HttpResponse::Ok()
|
|
|
|
.status(StatusCode::NO_CONTENT)
|
2017-12-04 05:09:46 +01:00
|
|
|
.header("X-TEST", "value")
|
2017-11-28 23:29:22 +01:00
|
|
|
.version(Version::HTTP_10)
|
|
|
|
.finish().unwrap();
|
|
|
|
assert_eq!(resp.version(), Some(Version::HTTP_10));
|
2017-12-04 03:15:09 +01:00
|
|
|
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
|
|
|
|
|
|
|
let _t = format!("{:?}", resp);
|
2017-11-28 23:29:22 +01:00
|
|
|
}
|
|
|
|
|
2017-10-23 07:54:11 +02:00
|
|
|
#[test]
|
|
|
|
fn test_upgrade() {
|
2017-11-27 07:31:29 +01:00
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
2017-10-23 07:54:11 +02:00
|
|
|
.upgrade().body(Body::Empty).unwrap();
|
|
|
|
assert!(resp.upgrade())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_force_close() {
|
2017-11-27 07:31:29 +01:00
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
2017-10-23 07:54:11 +02:00
|
|
|
.force_close().body(Body::Empty).unwrap();
|
|
|
|
assert!(!resp.keep_alive().unwrap())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_content_type() {
|
2017-11-27 07:31:29 +01:00
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
2017-10-23 07:54:11 +02:00
|
|
|
.content_type("text/plain").body(Body::Empty).unwrap();
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/plain")
|
|
|
|
}
|
2017-11-06 23:56:38 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_content_encoding() {
|
2017-11-27 07:31:29 +01:00
|
|
|
let resp = HttpResponse::build(StatusCode::OK).finish().unwrap();
|
2017-11-06 23:56:38 +01:00
|
|
|
assert_eq!(*resp.content_encoding(), ContentEncoding::Auto);
|
|
|
|
|
2017-11-27 07:31:29 +01:00
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
2017-11-06 23:56:38 +01:00
|
|
|
.content_encoding(ContentEncoding::Br).finish().unwrap();
|
|
|
|
assert_eq!(*resp.content_encoding(), ContentEncoding::Br);
|
2017-11-07 01:23:58 +01:00
|
|
|
}
|
2017-11-27 19:39:47 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_json() {
|
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
|
|
|
.json(vec!["v1", "v2", "v3"]).unwrap();
|
|
|
|
let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
|
|
|
|
assert_eq!(ct, header::HeaderValue::from_static("application/json"));
|
|
|
|
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_json_ct() {
|
|
|
|
let resp = HttpResponse::build(StatusCode::OK)
|
|
|
|
.header(header::CONTENT_TYPE, "text/json")
|
|
|
|
.json(vec!["v1", "v2", "v3"]).unwrap();
|
|
|
|
let ct = resp.headers().get(header::CONTENT_TYPE).unwrap();
|
|
|
|
assert_eq!(ct, header::HeaderValue::from_static("text/json"));
|
|
|
|
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
|
|
|
|
}
|
2017-11-28 22:52:53 +01:00
|
|
|
|
|
|
|
impl Body {
|
|
|
|
pub(crate) fn binary(&self) -> Option<&Binary> {
|
|
|
|
match *self {
|
|
|
|
Body::Binary(ref bin) => Some(bin),
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_into_response() {
|
2017-12-03 23:22:04 +01:00
|
|
|
let req = HttpRequest::default();
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let resp: HttpResponse = "test".into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test"));
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
let resp: HttpResponse = "test".from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test"));
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let resp: HttpResponse = b"test".as_ref().into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(b"test".as_ref()));
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
let resp: HttpResponse = b"test".as_ref().from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(b"test".as_ref()));
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let resp: HttpResponse = "test".to_owned().into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test".to_owned()));
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
let resp: HttpResponse = "test".to_owned().from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test".to_owned()));
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let resp: HttpResponse = (&"test".to_owned()).into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from((&"test".to_owned())));
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
let resp: HttpResponse = (&"test".to_owned()).from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("text/plain; charset=utf-8"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from((&"test".to_owned())));
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let b = Bytes::from_static(b"test");
|
|
|
|
let resp: HttpResponse = b.into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(Bytes::from_static(b"test")));
|
|
|
|
|
2017-12-03 23:22:04 +01:00
|
|
|
let b = Bytes::from_static(b"test");
|
|
|
|
let resp: HttpResponse = b.from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(Bytes::from_static(b"test")));
|
|
|
|
|
2017-11-28 22:52:53 +01:00
|
|
|
let b = BytesMut::from("test");
|
|
|
|
let resp: HttpResponse = b.into();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(BytesMut::from("test")));
|
2017-12-03 23:22:04 +01:00
|
|
|
|
|
|
|
let b = BytesMut::from("test");
|
|
|
|
let resp: HttpResponse = b.from_request(req.clone()).ok().unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
|
|
|
|
header::HeaderValue::from_static("application/octet-stream"));
|
|
|
|
assert_eq!(resp.status(), StatusCode::OK);
|
|
|
|
assert_eq!(resp.body().binary().unwrap(), &Binary::from(BytesMut::from("test")));
|
2017-11-28 22:52:53 +01:00
|
|
|
}
|
2017-10-23 07:54:11 +02:00
|
|
|
}
|