1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-24 16:32:59 +01:00
actix-web/src/response.rs

994 lines
29 KiB
Rust
Raw Normal View History

2018-01-28 07:03:03 +01:00
//! Http response
2018-04-14 01:02:01 +02:00
use std::io::Write;
2018-11-18 05:21:28 +01:00
use std::{fmt, str};
2017-10-07 06:48:14 +02:00
2018-04-14 01:02:01 +02:00
use bytes::{BufMut, Bytes, BytesMut};
2018-01-28 07:03:03 +01:00
use cookie::{Cookie, CookieJar};
2018-03-08 02:40:13 +01:00
use futures::Stream;
2017-10-10 08:07:32 +02:00
use http::header::{self, HeaderName, HeaderValue};
2019-02-08 06:16:46 +01:00
use http::{Error as HttpError, HeaderMap, HttpTryFrom, StatusCode};
2017-11-27 19:39:47 +01:00
use serde::Serialize;
2018-04-14 01:02:01 +02:00
use serde_json;
2017-12-08 01:40:29 +01:00
2018-12-06 23:32:52 +01:00
use crate::body::{Body, BodyStream, MessageBody, ResponseBody};
use crate::error::Error;
use crate::header::{Header, IntoHeaderValue};
2019-02-08 06:16:46 +01:00
use crate::message::{ConnectionType, Head, Message, ResponseHead};
2018-03-09 19:00:15 +01:00
2017-12-16 01:24:15 +01:00
/// An HTTP Response
2019-02-08 06:16:46 +01:00
pub struct Response<B: MessageBody = Body> {
head: Message<ResponseHead>,
body: ResponseBody<B>,
error: Option<Error>,
}
2017-12-16 01:24:15 +01:00
impl Response<Body> {
2017-11-27 07:31:29 +01:00
/// Create http response builder with specific status.
2017-10-11 01:03:32 +02:00
#[inline]
2018-10-05 20:04:59 +02:00
pub fn build(status: StatusCode) -> ResponseBuilder {
2019-02-08 06:16:46 +01:00
ResponseBuilder::new(status)
2017-10-11 01:03:32 +02:00
}
/// Create http response builder
#[inline]
2018-10-05 20:04:59 +02:00
pub fn build_from<T: Into<ResponseBuilder>>(source: T) -> ResponseBuilder {
source.into()
}
2017-10-07 08:14:13 +02:00
/// Constructs a response
2017-10-07 06:48:14 +02:00
#[inline]
2018-10-05 20:04:59 +02:00
pub fn new(status: StatusCode) -> Response {
2019-02-08 06:16:46 +01:00
let mut head: Message<ResponseHead> = Message::new();
head.status = status;
Response {
head,
body: ResponseBody::Body(Body::Empty),
error: None,
}
2017-10-07 06:48:14 +02:00
}
2018-05-29 18:11:10 +02:00
/// Constructs an error response
2017-11-25 18:03:44 +01:00
#[inline]
2018-10-05 20:04:59 +02:00
pub fn from_error(error: Error) -> Response {
let mut resp = error.as_response_error().error_response();
2019-02-08 06:16:46 +01:00
resp.error = Some(error);
2017-11-25 18:03:44 +01:00
resp
}
2018-10-05 20:04:59 +02:00
/// Convert `Response` to a `ResponseBuilder`
#[inline]
2018-10-05 20:04:59 +02:00
pub fn into_builder(self) -> ResponseBuilder {
2018-06-12 15:49:07 +02:00
// If this response has cookies, load them into a jar
let mut jar: Option<CookieJar> = None;
for c in self.cookies() {
if let Some(ref mut j) = jar {
j.add_original(c.into_owned());
} else {
let mut j = CookieJar::new();
j.add_original(c.into_owned());
jar = Some(j);
}
}
2018-10-05 20:04:59 +02:00
ResponseBuilder {
2019-02-08 06:16:46 +01:00
head: Some(self.head),
err: None,
2018-06-12 15:49:07 +02:00
cookies: jar,
}
}
2018-11-21 16:49:24 +01:00
/// Convert response to response with body
pub fn into_body<B: MessageBody>(self) -> Response<B> {
2019-02-08 06:16:46 +01:00
let b = match self.body {
2018-11-21 16:49:24 +01:00
ResponseBody::Body(b) => b,
ResponseBody::Other(b) => b,
};
2019-02-08 06:16:46 +01:00
Response {
head: self.head,
error: self.error,
body: ResponseBody::Other(b),
}
2018-11-21 16:49:24 +01:00
}
2018-11-18 05:21:28 +01:00
}
impl<B: MessageBody> Response<B> {
#[inline]
2018-11-19 23:57:12 +01:00
/// Http message part of the response
pub fn head(&self) -> &ResponseHead {
2019-02-08 06:16:46 +01:00
&*self.head
2018-11-19 23:57:12 +01:00
}
#[inline]
/// Mutable reference to a http message part of the response
pub fn head_mut(&mut self) -> &mut ResponseHead {
2019-02-08 06:16:46 +01:00
&mut *self.head
2018-11-18 05:21:28 +01:00
}
/// Constructs a response with body
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Response<B> {
2019-02-08 06:16:46 +01:00
let mut head: Message<ResponseHead> = Message::new();
head.status = status;
Response {
head,
body: ResponseBody::Body(body),
error: None,
}
2018-11-18 05:21:28 +01:00
}
2017-11-25 18:03:44 +01:00
/// The source `error` for this response
#[inline]
pub fn error(&self) -> Option<&Error> {
2019-02-08 06:16:46 +01:00
self.error.as_ref()
2017-11-25 18:03:44 +01:00
}
2018-11-18 05:21:28 +01:00
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
2019-02-08 06:16:46 +01:00
self.head.status
2018-11-18 05:21:28 +01:00
}
/// Set the `StatusCode` for this response
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
2019-02-08 06:16:46 +01:00
&mut self.head.status
2018-11-18 05:21:28 +01:00
}
/// Get the headers from the response
2017-10-07 06:48:14 +02:00
#[inline]
2017-10-10 08:07:32 +02:00
pub fn headers(&self) -> &HeaderMap {
2019-02-08 06:16:46 +01:00
&self.head.headers
2017-10-07 06:48:14 +02:00
}
/// Get a mutable reference to the headers
2017-10-07 06:48:14 +02:00
#[inline]
2017-10-10 08:07:32 +02:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2019-02-08 06:16:46 +01:00
&mut self.head.headers
2017-10-07 06:48:14 +02:00
}
2018-06-12 15:49:07 +02:00
/// Get an iterator for the cookies set by this response
#[inline]
pub fn cookies(&self) -> CookieIter {
CookieIter {
2019-02-08 06:16:46 +01:00
iter: self.head.headers.get_all(header::SET_COOKIE).iter(),
2018-06-12 15:49:07 +02:00
}
}
/// Add a cookie to this response
#[inline]
2018-06-14 08:37:19 +02:00
pub fn add_cookie(&mut self, cookie: &Cookie) -> Result<(), HttpError> {
2019-02-08 06:16:46 +01:00
let h = &mut self.head.headers;
2018-06-12 15:49:07 +02:00
HeaderValue::from_str(&cookie.to_string())
2018-06-14 08:37:19 +02:00
.map(|c| {
h.append(header::SET_COOKIE, c);
2018-12-06 23:32:52 +01:00
})
.map_err(|e| e.into())
2018-06-12 15:49:07 +02:00
}
/// Remove all cookies with the given name from this response. Returns
/// the number of cookies removed.
#[inline]
pub fn del_cookie(&mut self, name: &str) -> usize {
2019-02-08 06:16:46 +01:00
let h = &mut self.head.headers;
2018-06-14 08:37:19 +02:00
let vals: Vec<HeaderValue> = h
.get_all(header::SET_COOKIE)
2018-06-12 15:49:07 +02:00
.iter()
.map(|v| v.to_owned())
.collect();
h.remove(header::SET_COOKIE);
let mut count: usize = 0;
for v in vals {
if let Ok(s) = v.to_str() {
if let Ok(c) = Cookie::parse_encoded(s) {
2018-06-12 15:49:07 +02:00
if c.name() == name {
count += 1;
continue;
}
}
}
h.append(header::SET_COOKIE, v);
}
2018-06-14 08:37:19 +02:00
count
2018-06-12 15:49:07 +02:00
}
2017-10-08 06:48:00 +02:00
/// Connection upgrade status
2018-01-01 02:26:32 +01:00
#[inline]
2017-10-08 06:48:00 +02:00
pub fn upgrade(&self) -> bool {
2019-02-08 06:16:46 +01:00
self.head.upgrade()
2017-10-08 06:48:00 +02:00
}
2017-10-07 06:48:14 +02:00
/// Keep-alive status for this connection
2018-11-19 02:52:56 +01:00
pub fn keep_alive(&self) -> bool {
2019-02-08 06:16:46 +01:00
self.head.keep_alive()
2017-10-07 06:48:14 +02:00
}
2017-10-08 06:48:00 +02:00
2017-10-07 08:14:13 +02:00
/// Get body os this response
2018-01-01 02:26:32 +01:00
#[inline]
2019-02-08 06:16:46 +01:00
pub fn body(&self) -> &ResponseBody<B> {
&self.body
2017-10-07 06:48:14 +02:00
}
2017-10-08 06:48:00 +02:00
/// Set a body
2018-11-21 16:49:24 +01:00
pub(crate) fn set_body<B2: MessageBody>(self, body: B2) -> Response<B2> {
2019-02-08 06:16:46 +01:00
Response {
head: self.head,
body: ResponseBody::Body(body),
error: None,
}
2017-10-08 06:48:00 +02:00
}
/// Drop request's body
2018-11-21 16:49:24 +01:00
pub(crate) fn drop_body(self) -> Response<()> {
2019-02-08 06:16:46 +01:00
Response {
head: self.head,
body: ResponseBody::Body(()),
error: None,
}
}
2017-10-07 08:14:13 +02:00
/// Set a body and return previous body value
2018-11-21 16:49:24 +01:00
pub(crate) fn replace_body<B2: MessageBody>(
self,
body: B2,
) -> (Response<B2>, ResponseBody<B>) {
2019-02-08 06:16:46 +01:00
(
Response {
head: self.head,
body: ResponseBody::Body(body),
error: self.error,
},
self.body,
)
2018-06-25 06:10:02 +02:00
}
2019-02-19 02:01:35 +01:00
/// Set a body and return previous body value
pub fn map_body<F, B2: MessageBody>(mut self, f: F) -> Response<B2>
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
let body = f(&mut self.head, self.body);
Response {
head: self.head,
body: body,
error: self.error,
}
}
2017-10-07 06:48:14 +02:00
}
2017-10-11 01:03:32 +02:00
2018-11-19 02:52:56 +01:00
impl<B: MessageBody> fmt::Debug for Response<B> {
2017-11-09 04:31:25 +01:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2018-04-14 01:02:01 +02:00
let res = writeln!(
f,
2018-10-05 20:04:59 +02:00
"\nResponse {:?} {}{}",
2019-02-08 06:16:46 +01:00
self.head.version,
self.head.status,
self.head.reason.unwrap_or(""),
2018-04-14 01:02:01 +02:00
);
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " headers:");
2019-02-08 06:16:46 +01:00
for (key, val) in self.head.headers.iter() {
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " {:?}: {:?}", key, val);
2017-11-09 04:31:25 +01:00
}
2019-02-08 06:16:46 +01:00
let _ = writeln!(f, " body: {:?}", self.body.length());
2017-11-09 04:31:25 +01:00
res
}
}
2018-06-12 15:49:07 +02:00
pub struct CookieIter<'a> {
iter: header::ValueIter<'a, HeaderValue>,
}
impl<'a> Iterator for CookieIter<'a> {
type Item = Cookie<'a>;
#[inline]
fn next(&mut self) -> Option<Cookie<'a>> {
for v in self.iter.by_ref() {
if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) {
2018-06-12 15:49:07 +02:00
return Some(c);
}
}
None
}
}
2017-10-11 01:03:32 +02:00
/// An HTTP response builder
///
2018-10-05 20:04:59 +02:00
/// This type can be used to construct an instance of `Response` through a
2017-10-11 01:03:32 +02:00
/// builder-like pattern.
2018-10-05 20:04:59 +02:00
pub struct ResponseBuilder {
2019-02-08 06:16:46 +01:00
head: Option<Message<ResponseHead>>,
2017-10-22 18:13:29 +02:00
err: Option<HttpError>,
2017-12-14 01:44:35 +01:00
cookies: Option<CookieJar>,
2017-10-11 01:03:32 +02:00
}
2018-10-05 20:04:59 +02:00
impl ResponseBuilder {
2019-02-08 06:16:46 +01:00
/// Create response builder
pub fn new(status: StatusCode) -> Self {
let mut head: Message<ResponseHead> = Message::new();
head.status = status;
ResponseBuilder {
head: Some(head),
err: None,
cookies: None,
}
}
2018-03-06 09:43:25 +01:00
/// Set HTTP status code of this response.
#[inline]
pub fn status(&mut self, status: StatusCode) -> &mut Self {
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.status = status;
2018-03-06 09:43:25 +01:00
}
self
}
2018-03-06 04:28:42 +01:00
/// Set a header.
///
2018-10-05 06:14:18 +02:00
/// ```rust,ignore
2018-03-06 04:28:42 +01:00
/// # extern crate actix_web;
2018-10-05 20:04:59 +02:00
/// use actix_web::{http, Request, Response, Result};
2018-03-06 04:28:42 +01:00
///
2018-10-05 20:04:59 +02:00
/// fn index(req: HttpRequest) -> Result<Response> {
/// Ok(Response::Ok()
2018-06-01 18:37:14 +02:00
/// .set(http::header::IfModifiedSince(
/// "Sun, 07 Nov 1994 08:48:37 GMT".parse()?,
/// ))
/// .finish())
2018-03-06 04:28:42 +01:00
/// }
/// fn main() {}
/// ```
#[doc(hidden)]
2018-04-14 01:02:01 +02:00
pub fn set<H: Header>(&mut self, hdr: H) -> &mut Self {
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
2018-03-06 04:28:42 +01:00
match hdr.try_into() {
2018-04-14 01:02:01 +02:00
Ok(value) => {
2019-02-08 06:16:46 +01:00
parts.headers.append(H::name(), value);
2018-04-14 01:02:01 +02:00
}
2018-03-06 04:28:42 +01:00
Err(e) => self.err = Some(e.into()),
}
}
self
}
2018-11-19 23:57:12 +01:00
/// Append a header to existing headers.
2017-12-21 08:19:21 +01:00
///
2018-10-05 06:14:18 +02:00
/// ```rust,ignore
2017-12-21 08:19:21 +01:00
/// # extern crate actix_web;
2018-10-05 20:04:59 +02:00
/// use actix_web::{http, Request, Response};
2017-12-21 08:19:21 +01:00
///
2018-10-05 20:04:59 +02:00
/// fn index(req: HttpRequest) -> Response {
/// Response::Ok()
2017-12-21 08:19:21 +01:00
/// .header("X-TEST", "value")
/// .header(http::header::CONTENT_TYPE, "application/json")
/// .finish()
2017-12-21 08:19:21 +01:00
/// }
/// fn main() {}
/// ```
2017-10-11 01:03:32 +02:00
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
2018-04-14 01:02:01 +02:00
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
2017-10-11 01:03:32 +02:00
{
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
2017-10-11 01:03:32 +02:00
match HeaderName::try_from(key) {
2018-04-14 01:02:01 +02:00
Ok(key) => match value.try_into() {
Ok(value) => {
2019-02-08 06:16:46 +01:00
parts.headers.append(key, value);
2017-10-11 01:03:32 +02:00
}
2018-04-14 01:02:01 +02:00
Err(e) => self.err = Some(e.into()),
2017-10-11 01:03:32 +02:00
},
Err(e) => self.err = Some(e.into()),
};
}
self
}
2018-11-19 23:57:12 +01:00
/// Set a header.
///
/// ```rust,ignore
/// # extern crate actix_web;
/// use actix_web::{http, Request, Response};
///
/// fn index(req: HttpRequest) -> Response {
/// Response::Ok()
/// .set_header("X-TEST", "value")
/// .set_header(http::header::CONTENT_TYPE, "application/json")
/// .finish()
/// }
/// fn main() {}
/// ```
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
where
HeaderName: HttpTryFrom<K>,
V: IntoHeaderValue,
{
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
2018-11-19 23:57:12 +01:00
match HeaderName::try_from(key) {
Ok(key) => match value.try_into() {
Ok(value) => {
2019-02-08 06:16:46 +01:00
parts.headers.insert(key, value);
2018-11-19 23:57:12 +01:00
}
Err(e) => self.err = Some(e.into()),
},
Err(e) => self.err = Some(e.into()),
};
}
self
}
2017-10-11 01:03:32 +02:00
/// Set the custom reason for the response.
#[inline]
pub fn reason(&mut self, reason: &'static str) -> &mut Self {
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.reason = Some(reason);
2017-10-11 01:03:32 +02:00
}
self
}
2018-11-19 02:52:56 +01:00
/// Set connection type to KeepAlive
2017-12-04 05:47:15 +01:00
#[inline]
2018-11-19 02:52:56 +01:00
pub fn keep_alive(&mut self) -> &mut Self {
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.set_connection_type(ConnectionType::KeepAlive);
2017-10-11 01:03:32 +02:00
}
self
}
2017-10-14 19:01:53 +02:00
/// Set connection type to Upgrade
2017-12-04 05:47:15 +01:00
#[inline]
2018-11-19 23:57:12 +01:00
pub fn upgrade<V>(&mut self, value: V) -> &mut Self
where
V: IntoHeaderValue,
{
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.set_connection_type(ConnectionType::Upgrade);
2018-11-19 02:52:56 +01:00
}
2018-11-19 23:57:12 +01:00
self.set_header(header::UPGRADE, value)
2017-10-14 19:01:53 +02:00
}
/// 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 {
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.set_connection_type(ConnectionType::Close);
2018-11-19 02:52:56 +01:00
}
self
2017-10-14 19:01:53 +02:00
}
2019-02-19 05:24:50 +01:00
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
#[inline]
pub fn no_chunking(&mut self) -> &mut Self {
if let Some(parts) = parts(&mut self.head, &self.err) {
parts.no_chunking = 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
2018-04-14 01:02:01 +02:00
where
HeaderValue: HttpTryFrom<V>,
2017-10-14 19:01:53 +02:00
{
2019-02-08 06:16:46 +01:00
if let Some(parts) = parts(&mut self.head, &self.err) {
2017-10-14 19:01:53 +02:00
match HeaderValue::try_from(value) {
2018-04-14 01:02:01 +02:00
Ok(value) => {
2019-02-08 06:16:46 +01:00
parts.headers.insert(header::CONTENT_TYPE, value);
2018-04-14 01:02:01 +02:00
}
2017-10-14 19:01:53 +02:00
Err(e) => self.err = Some(e.into()),
};
}
self
}
2018-01-12 01:22:27 +01:00
/// Set content length
#[inline]
pub fn content_length(&mut self, len: u64) -> &mut Self {
let mut wrt = BytesMut::new().writer();
let _ = write!(wrt, "{}", len);
self.header(header::CONTENT_LENGTH, wrt.get_mut().take().freeze())
}
2017-10-14 19:40:58 +02:00
/// Set a cookie
2017-12-21 08:19:21 +01:00
///
2018-10-05 06:14:18 +02:00
/// ```rust,ignore
2017-12-21 08:19:21 +01:00
/// # extern crate actix_web;
2018-10-05 20:04:59 +02:00
/// use actix_web::{http, HttpRequest, Response, Result};
2017-12-21 08:19:21 +01:00
///
2018-10-05 20:04:59 +02:00
/// fn index(req: HttpRequest) -> Response {
/// Response::Ok()
2017-12-21 08:19:21 +01:00
/// .cookie(
2018-03-31 02:31:18 +02:00
/// http::Cookie::build("name", "value")
2017-12-21 08:19:21 +01:00
/// .domain("www.rust-lang.org")
/// .path("/")
/// .secure(true)
/// .http_only(true)
2018-06-01 18:37:14 +02:00
/// .finish(),
/// )
/// .finish()
2017-12-21 08:19:21 +01:00
/// }
/// ```
2017-10-14 19:40:58 +02:00
pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self {
2017-12-14 01:44:35 +01:00
if self.cookies.is_none() {
let mut jar = CookieJar::new();
jar.add(cookie.into_owned());
self.cookies = Some(jar)
} else {
2018-05-16 01:41:46 +02:00
self.cookies.as_mut().unwrap().add(cookie.into_owned());
2017-10-14 19:40:58 +02:00
}
self
}
/// Remove cookie
///
2018-10-05 06:14:18 +02:00
/// ```rust,ignore
/// # extern crate actix_web;
2018-10-05 20:04:59 +02:00
/// use actix_web::{http, HttpRequest, Response, Result};
///
2018-10-05 20:04:59 +02:00
/// fn index(req: &HttpRequest) -> Response {
/// let mut builder = Response::Ok();
///
2018-06-25 06:58:04 +02:00
/// if let Some(ref cookie) = req.cookie("name") {
/// builder.del_cookie(cookie);
/// }
///
/// builder.finish()
/// }
/// ```
2017-10-14 19:40:58 +02:00
pub fn del_cookie<'a>(&mut self, cookie: &Cookie<'a>) -> &mut Self {
2017-12-14 01:44:35 +01:00
{
if self.cookies.is_none() {
self.cookies = Some(CookieJar::new())
2017-12-13 06:32:58 +01:00
}
2017-12-14 01:44:35 +01:00
let jar = self.cookies.as_mut().unwrap();
2017-10-14 19:40:58 +02:00
let cookie = cookie.clone().into_owned();
2017-12-13 06:32:58 +01:00
jar.add_original(cookie.clone());
jar.remove(cookie);
2017-10-14 19:40:58 +02:00
}
self
}
2018-04-14 01:02:01 +02:00
/// This method 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
2018-04-14 01:02:01 +02:00
where
2018-10-05 20:04:59 +02:00
F: FnOnce(&mut ResponseBuilder),
2017-10-29 22:51:02 +01:00
{
if value {
f(self);
}
self
}
2018-04-14 01:02:01 +02:00
/// This method calls provided closure with builder reference if value is
/// Some.
pub fn if_some<T, F>(&mut self, value: Option<T>, f: F) -> &mut Self
2018-04-14 01:02:01 +02:00
where
2018-10-05 20:04:59 +02:00
F: FnOnce(T, &mut ResponseBuilder),
2018-01-10 08:55:42 +01:00
{
if let Some(val) = value {
f(val, self);
}
self
}
2018-10-05 20:04:59 +02:00
/// Set a body and generate `Response`.
2017-12-21 08:19:21 +01:00
///
2018-10-05 20:04:59 +02:00
/// `ResponseBuilder` can not be used after this call.
pub fn body<B: Into<Body>>(&mut self, body: B) -> Response {
self.message_body(body.into())
}
/// Set a body and generate `Response`.
///
/// `ResponseBuilder` can not be used after this call.
pub fn message_body<B: MessageBody>(&mut self, body: B) -> Response<B> {
2018-11-21 16:49:24 +01:00
if let Some(e) = self.err.take() {
return Response::from(Error::from(e)).into_body();
}
2018-11-18 05:21:28 +01:00
2019-02-08 06:16:46 +01:00
let mut response = self.head.take().expect("cannot reuse response builder");
2017-12-14 01:44:35 +01:00
if let Some(ref jar) = self.cookies {
2017-12-13 06:32:58 +01:00
for cookie in jar.delta() {
match HeaderValue::from_str(&cookie.to_string()) {
2018-11-18 05:21:28 +01:00
Ok(val) => {
2019-02-08 06:16:46 +01:00
let _ = response.headers.append(header::SET_COOKIE, val);
2018-11-18 05:21:28 +01:00
}
2018-11-21 16:49:24 +01:00
Err(e) => return Response::from(Error::from(e)).into_body(),
};
2017-12-13 06:32:58 +01:00
}
2017-10-14 19:40:58 +02:00
}
2018-11-18 05:21:28 +01:00
2019-02-08 06:16:46 +01:00
Response {
head: response,
body: ResponseBody::Body(body),
error: None,
}
2017-10-11 01:03:32 +02:00
}
2017-10-24 08:52:20 +02:00
#[inline]
2018-10-05 20:04:59 +02:00
/// Set a streaming body and generate `Response`.
2018-03-08 02:40:13 +01:00
///
2018-10-05 20:04:59 +02:00
/// `ResponseBuilder` can not be used after this call.
pub fn streaming<S, E>(&mut self, stream: S) -> Response
2018-04-14 01:02:01 +02:00
where
S: Stream<Item = Bytes, Error = E> + 'static,
E: Into<Error> + 'static,
2018-03-08 02:40:13 +01:00
{
self.body(Body::from_message(BodyStream::new(stream)))
2018-03-08 02:40:13 +01:00
}
2018-10-05 20:04:59 +02:00
/// Set a json body and generate `Response`
2017-12-21 08:19:21 +01:00
///
2018-10-05 20:04:59 +02:00
/// `ResponseBuilder` can not be used after this call.
pub fn json<T: Serialize>(&mut self, value: T) -> Response {
2018-08-08 19:11:15 +02:00
self.json2(&value)
}
2018-10-05 20:04:59 +02:00
/// Set a json body and generate `Response`
2018-08-08 19:11:15 +02:00
///
2018-10-05 20:04:59 +02:00
/// `ResponseBuilder` can not be used after this call.
pub fn json2<T: Serialize>(&mut self, value: &T) -> Response {
2018-08-08 19:11:15 +02:00
match serde_json::to_string(value) {
Ok(body) => {
2019-02-08 06:16:46 +01:00
let contains = if let Some(parts) = parts(&mut self.head, &self.err) {
parts.headers.contains_key(header::CONTENT_TYPE)
2018-04-14 01:02:01 +02:00
} else {
true
};
if !contains {
self.header(header::CONTENT_TYPE, "application/json");
}
self.body(Body::from(body))
2018-11-18 05:21:28 +01:00
}
Err(e) => Error::from(e).into(),
2017-11-27 19:39:47 +01:00
}
}
#[inline]
2018-10-05 20:04:59 +02:00
/// Set an empty body and generate `Response`
2017-12-21 08:19:21 +01:00
///
2018-10-05 20:04:59 +02:00
/// `ResponseBuilder` can not be used after this call.
pub fn finish(&mut self) -> Response {
self.body(Body::Empty)
2017-10-24 08:52:20 +02:00
}
2018-01-01 02:26:32 +01:00
2018-10-05 20:04:59 +02:00
/// This method construct new `ResponseBuilder`
pub fn take(&mut self) -> ResponseBuilder {
ResponseBuilder {
2019-02-08 06:16:46 +01:00
head: self.head.take(),
2018-01-01 02:26:32 +01:00
err: self.err.take(),
cookies: self.cookies.take(),
}
}
2017-10-11 01:03:32 +02:00
}
2017-12-16 05:00:12 +01:00
#[inline]
2019-01-29 19:14:00 +01:00
#[allow(clippy::borrowed_box)]
2018-04-14 01:02:01 +02:00
fn parts<'a>(
2019-02-08 06:16:46 +01:00
parts: &'a mut Option<Message<ResponseHead>>,
2018-10-30 00:39:46 +01:00
err: &Option<HttpError>,
2019-02-08 06:16:46 +01:00
) -> Option<&'a mut Message<ResponseHead>> {
2017-10-11 01:03:32 +02:00
if err.is_some() {
2018-04-14 01:02:01 +02:00
return None;
2017-10-11 01:03:32 +02:00
}
parts.as_mut()
}
2017-10-23 07:54:11 +02:00
2017-11-28 22:52:53 +01:00
/// Helper converters
2018-10-05 20:04:59 +02:00
impl<I: Into<Response>, E: Into<Error>> From<Result<I, E>> for Response {
2017-11-28 22:52:53 +01:00
fn from(res: Result<I, E>) -> Self {
match res {
Ok(val) => val.into(),
Err(err) => err.into().into(),
}
}
}
2018-10-05 20:04:59 +02:00
impl From<ResponseBuilder> for Response {
fn from(mut builder: ResponseBuilder) -> Self {
builder.finish()
2017-11-29 18:17:00 +01:00
}
}
impl From<&'static str> for Response {
2017-11-29 18:17:00 +01:00
fn from(val: &'static str) -> Self {
2018-10-05 20:04:59 +02:00
Response::Ok()
2018-04-29 18:09:08 +02:00
.content_type("text/plain; charset=utf-8")
.body(val)
2017-11-28 22:52:53 +01:00
}
}
impl From<&'static [u8]> for Response {
2017-11-29 18:17:00 +01:00
fn from(val: &'static [u8]) -> Self {
2018-10-05 20:04:59 +02:00
Response::Ok()
2018-04-29 18:09:08 +02:00
.content_type("application/octet-stream")
.body(val)
2017-11-28 22:52:53 +01:00
}
}
impl From<String> for Response {
2017-11-29 18:17:00 +01:00
fn from(val: String) -> Self {
2018-10-05 20:04:59 +02:00
Response::Ok()
2018-04-29 18:09:08 +02:00
.content_type("text/plain; charset=utf-8")
.body(val)
2017-11-28 22:52:53 +01:00
}
}
impl<'a> From<&'a String> for Response {
fn from(val: &'a String) -> Self {
Response::Ok()
.content_type("text/plain; charset=utf-8")
.body(val)
}
}
impl From<Bytes> for Response {
2017-11-29 18:17:00 +01:00
fn from(val: Bytes) -> Self {
2018-10-05 20:04:59 +02:00
Response::Ok()
2018-04-29 18:09:08 +02:00
.content_type("application/octet-stream")
.body(val)
2017-11-28 22:52:53 +01:00
}
}
impl From<BytesMut> for Response {
2017-11-29 18:17:00 +01:00
fn from(val: BytesMut) -> Self {
2018-10-05 20:04:59 +02:00
Response::Ok()
2018-04-29 18:09:08 +02:00
.content_type("application/octet-stream")
.body(val)
2017-11-28 22:52:53 +01:00
}
}
2017-10-23 07:54:11 +02:00
#[cfg(test)]
mod tests {
use super::*;
2018-12-07 00:03:01 +01:00
use crate::body::Body;
use crate::http;
use crate::http::header::{HeaderValue, CONTENT_TYPE, COOKIE};
2017-12-13 20:16:26 +01:00
2018-10-07 06:14:02 +02:00
// use test::TestRequest;
2018-06-25 06:58:04 +02:00
2017-12-13 20:16:26 +01:00
#[test]
fn test_debug() {
2018-10-05 20:04:59 +02:00
let resp = Response::Ok()
2018-03-08 07:40:46 +01:00
.header(COOKIE, HeaderValue::from_static("cookie1=value1; "))
.header(COOKIE, HeaderValue::from_static("cookie2=value2; "))
.finish();
2017-12-13 20:16:26 +01:00
let dbg = format!("{:?}", resp);
2018-10-05 20:04:59 +02:00
assert!(dbg.contains("Response"));
2017-12-13 20:16:26 +01:00
}
2018-10-05 06:14:18 +02:00
// #[test]
// fn test_response_cookies() {
// let req = TestRequest::default()
// .header(COOKIE, "cookie1=value1")
// .header(COOKIE, "cookie2=value2")
// .finish();
// let cookies = req.cookies().unwrap();
2018-10-05 20:04:59 +02:00
// let resp = Response::Ok()
2018-10-05 06:14:18 +02:00
// .cookie(
// http::Cookie::build("name", "value")
// .domain("www.rust-lang.org")
// .path("/test")
// .http_only(true)
// .max_age(Duration::days(1))
// .finish(),
// ).del_cookie(&cookies[0])
// .finish();
// let mut val: Vec<_> = resp
// .headers()
// .get_all("Set-Cookie")
// .iter()
// .map(|v| v.to_str().unwrap().to_owned())
// .collect();
// val.sort();
// assert!(val[0].starts_with("cookie1=; Max-Age=0;"));
// assert_eq!(
// val[1],
// "name=value; HttpOnly; Path=/test; Domain=www.rust-lang.org; Max-Age=86400"
// );
// }
2017-10-23 07:54:11 +02:00
2018-06-12 15:49:07 +02:00
#[test]
fn test_update_response_cookies() {
2018-10-05 20:04:59 +02:00
let mut r = Response::Ok()
2018-06-12 15:49:07 +02:00
.cookie(http::Cookie::new("original", "val100"))
.finish();
2018-06-14 08:37:19 +02:00
r.add_cookie(&http::Cookie::new("cookie2", "val200"))
.unwrap();
r.add_cookie(&http::Cookie::new("cookie2", "val250"))
.unwrap();
r.add_cookie(&http::Cookie::new("cookie3", "val300"))
.unwrap();
2018-06-12 15:49:07 +02:00
assert_eq!(r.cookies().count(), 4);
r.del_cookie("cookie2");
let mut iter = r.cookies();
let v = iter.next().unwrap();
assert_eq!((v.name(), v.value()), ("original", "val100"));
let v = iter.next().unwrap();
assert_eq!((v.name(), v.value()), ("cookie3", "val300"));
}
2017-11-28 23:29:22 +01:00
#[test]
fn test_basic_builder() {
let resp = Response::Ok().header("X-TEST", "value").finish();
2017-12-21 08:36:52 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2017-11-28 23:29:22 +01:00
}
2017-10-23 07:54:11 +02:00
#[test]
fn test_upgrade() {
2018-11-19 23:57:12 +01:00
let resp = Response::build(StatusCode::OK)
.upgrade("websocket")
.finish();
assert!(resp.upgrade());
assert_eq!(
resp.headers().get(header::UPGRADE).unwrap(),
HeaderValue::from_static("websocket")
);
2017-10-23 07:54:11 +02:00
}
#[test]
fn test_force_close() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK).force_close().finish();
2018-11-19 02:52:56 +01:00
assert!(!resp.keep_alive())
2017-10-23 07:54:11 +02:00
}
#[test]
fn test_content_type() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK)
2018-04-14 01:02:01 +02:00
.content_type("text/plain")
.body(Body::Empty);
2018-05-16 01:41:46 +02:00
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
2017-10-23 07:54:11 +02:00
}
// #[test]
// fn test_content_encoding() {
// let resp = Response::build(StatusCode::OK).finish();
// assert_eq!(resp.content_encoding(), None);
// #[cfg(feature = "brotli")]
// {
// let resp = Response::build(StatusCode::OK)
// .content_encoding(ContentEncoding::Br)
// .finish();
// assert_eq!(resp.content_encoding(), Some(ContentEncoding::Br));
// }
// let resp = Response::build(StatusCode::OK)
// .content_encoding(ContentEncoding::Gzip)
// .finish();
// assert_eq!(resp.content_encoding(), Some(ContentEncoding::Gzip));
// }
2017-11-27 19:39:47 +01:00
#[test]
fn test_json() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK).json(vec!["v1", "v2", "v3"]);
2018-03-06 04:28:42 +01:00
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
2018-03-06 09:43:25 +01:00
assert_eq!(ct, HeaderValue::from_static("application/json"));
2018-11-21 16:49:24 +01:00
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
2017-11-27 19:39:47 +01:00
}
#[test]
fn test_json_ct() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK)
2018-03-06 04:28:42 +01:00
.header(CONTENT_TYPE, "text/json")
.json(vec!["v1", "v2", "v3"]);
2018-03-06 04:28:42 +01:00
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
2018-03-06 09:43:25 +01:00
assert_eq!(ct, HeaderValue::from_static("text/json"));
2018-11-21 16:49:24 +01:00
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
2017-11-27 19:39:47 +01:00
}
2017-11-28 22:52:53 +01:00
2018-08-08 19:58:56 +02:00
#[test]
fn test_json2() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK).json2(&vec!["v1", "v2", "v3"]);
2018-08-08 19:58:56 +02:00
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json"));
2018-11-21 16:49:24 +01:00
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
2018-08-08 19:58:56 +02:00
}
#[test]
fn test_json2_ct() {
2018-10-05 20:04:59 +02:00
let resp = Response::build(StatusCode::OK)
2018-08-08 19:58:56 +02:00
.header(CONTENT_TYPE, "text/json")
.json2(&vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("text/json"));
2018-11-21 16:49:24 +01:00
assert_eq!(resp.body().get_ref(), b"[\"v1\",\"v2\",\"v3\"]");
2018-08-08 19:58:56 +02:00
}
2017-11-28 22:52:53 +01:00
#[test]
fn test_into_response() {
2018-10-05 20:04:59 +02:00
let resp: Response = "test".into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 22:52:53 +01:00
2018-10-05 20:04:59 +02:00
let resp: Response = b"test".as_ref().into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 22:52:53 +01:00
2018-10-05 20:04:59 +02:00
let resp: Response = "test".to_owned().into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2018-04-14 01:02:01 +02:00
2018-10-05 20:04:59 +02:00
let resp: Response = (&"test".to_owned()).into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2018-04-14 01:02:01 +02:00
2017-11-28 22:52:53 +01:00
let b = Bytes::from_static(b"test");
2018-10-05 20:04:59 +02:00
let resp: Response = b.into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 22:52:53 +01:00
let b = Bytes::from_static(b"test");
2018-10-05 20:04:59 +02:00
let resp: Response = b.into();
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 22:52:53 +01:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
let b = BytesMut::from("test");
2018-10-05 20:04:59 +02:00
let resp: Response = b.into();
assert_eq!(resp.status(), StatusCode::OK);
2018-04-14 01:02:01 +02:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 22:52:53 +01:00
}
#[test]
fn test_into_builder() {
2018-10-05 20:04:59 +02:00
let mut resp: Response = "test".into();
assert_eq!(resp.status(), StatusCode::OK);
2018-06-14 08:37:19 +02:00
resp.add_cookie(&http::Cookie::new("cookie1", "val100"))
.unwrap();
2018-06-12 15:49:07 +02:00
let mut builder = resp.into_builder();
let resp = builder.status(StatusCode::BAD_REQUEST).finish();
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
2018-06-12 15:49:07 +02:00
let cookie = resp.cookies().next().unwrap();
assert_eq!((cookie.name(), cookie.value()), ("cookie1", "val100"));
}
2017-10-23 07:54:11 +02:00
}