1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-13 10:49:26 +00:00
actix-web/actix-http/src/responses/response.rs

439 lines
13 KiB
Rust
Raw Normal View History

2021-04-14 01:12:47 +00:00
//! HTTP response.
2021-01-15 02:11:10 +00:00
use std::{
cell::{Ref, RefCell, RefMut},
fmt, str,
2021-01-15 02:11:10 +00:00
};
2017-10-07 04:48:14 +00:00
2019-12-05 17:35:43 +00:00
use bytes::{Bytes, BytesMut};
2021-12-04 19:40:47 +00:00
use bytestring::ByteString;
2017-12-08 00:40:29 +00:00
2021-02-13 15:08:43 +00:00
use crate::{
body::{BoxBody, EitherBody, MessageBody},
header::{self, HeaderMap, TryIntoHeaderValue},
2021-12-22 07:16:07 +00:00
responses::BoxedResponseHead,
Error, Extensions, ResponseBuilder, ResponseHead, StatusCode,
2021-02-13 15:08:43 +00:00
};
2018-03-09 18:00:15 +00:00
2021-04-14 01:12:47 +00:00
/// An HTTP response.
2021-04-13 10:16:12 +00:00
pub struct Response<B> {
2021-04-14 01:12:47 +00:00
pub(crate) head: BoxedResponseHead,
pub(crate) body: B,
pub(crate) extensions: RefCell<Extensions>,
2019-02-08 05:16:46 +00:00
}
2017-12-16 00:24:15 +00:00
2021-12-04 19:40:47 +00:00
impl Response<BoxBody> {
/// Constructs a new response with default body.
#[inline]
2021-06-17 16:57:58 +00:00
pub fn new(status: StatusCode) -> Self {
Response {
head: BoxedResponseHead::new(status),
2021-12-04 19:40:47 +00:00
body: BoxBody::new(()),
extensions: RefCell::new(Extensions::new()),
}
}
/// Constructs a new response builder.
2017-10-10 23:03:32 +00:00
#[inline]
2018-10-05 18:04:59 +00:00
pub fn build(status: StatusCode) -> ResponseBuilder {
2019-02-08 05:16:46 +00:00
ResponseBuilder::new(status)
2017-10-10 23:03:32 +00:00
}
// just a couple frequently used shortcuts
// this list should not grow larger than a few
/// Constructs a new response with status 200 OK.
#[inline]
2021-06-17 16:57:58 +00:00
pub fn ok() -> Self {
Response::new(StatusCode::OK)
}
/// Constructs a new response with status 400 Bad Request.
2017-10-07 04:48:14 +00:00
#[inline]
2021-06-17 16:57:58 +00:00
pub fn bad_request() -> Self {
Response::new(StatusCode::BAD_REQUEST)
}
/// Constructs a new response with status 404 Not Found.
#[inline]
2021-06-17 16:57:58 +00:00
pub fn not_found() -> Self {
Response::new(StatusCode::NOT_FOUND)
2017-10-07 04:48:14 +00:00
}
/// Constructs a new response with status 500 Internal Server Error.
#[inline]
2021-06-17 16:57:58 +00:00
pub fn internal_server_error() -> Self {
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
}
// end shortcuts
2018-11-18 04:21:28 +00:00
}
2019-02-21 05:05:37 +00:00
impl<B> Response<B> {
/// Constructs a new response with given body.
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Response<B> {
Response {
head: BoxedResponseHead::new(status),
2021-05-15 00:13:33 +00:00
body,
extensions: RefCell::new(Extensions::new()),
}
}
/// Returns a reference to the head of this response.
2018-11-18 04:21:28 +00:00
#[inline]
2018-11-19 22:57:12 +00:00
pub fn head(&self) -> &ResponseHead {
2019-02-08 05:16:46 +00:00
&*self.head
2018-11-19 22:57:12 +00:00
}
/// Returns a mutable reference to the head of this response.
2018-11-19 22:57:12 +00:00
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
2019-02-08 05:16:46 +00:00
&mut *self.head
2018-11-18 04:21:28 +00:00
}
/// Returns the status code of this response.
2018-11-18 04:21:28 +00:00
#[inline]
pub fn status(&self) -> StatusCode {
2019-02-08 05:16:46 +00:00
self.head.status
2018-11-18 04:21:28 +00:00
}
/// Returns a mutable reference the status code of this response.
2018-11-18 04:21:28 +00:00
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
2019-02-08 05:16:46 +00:00
&mut self.head.status
2018-11-18 04:21:28 +00:00
}
/// Returns a reference to response headers.
2017-10-07 04:48:14 +00:00
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers(&self) -> &HeaderMap {
2019-02-08 05:16:46 +00:00
&self.head.headers
2017-10-07 04:48:14 +00:00
}
/// Returns a mutable reference to response headers.
2017-10-07 04:48:14 +00:00
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2019-02-08 05:16:46 +00:00
&mut self.head.headers
2017-10-07 04:48:14 +00:00
}
/// Returns true if connection upgrade is enabled.
2018-01-01 01:26:32 +00:00
#[inline]
2017-10-08 04:48:00 +00:00
pub fn upgrade(&self) -> bool {
2019-02-08 05:16:46 +00:00
self.head.upgrade()
2017-10-08 04:48:00 +00:00
}
/// Returns true if keep-alive is enabled.
#[inline]
2018-11-19 01:52:56 +00:00
pub fn keep_alive(&self) -> bool {
2019-02-08 05:16:46 +00:00
self.head.keep_alive()
2017-10-07 04:48:14 +00:00
}
2017-10-08 04:48:00 +00:00
/// Returns a reference to the request-local data/extensions container.
2019-03-29 23:29:11 +00:00
#[inline]
2019-12-07 18:46:51 +00:00
pub fn extensions(&self) -> Ref<'_, Extensions> {
self.extensions.borrow()
2019-03-29 23:29:11 +00:00
}
/// Returns a mutable reference to the request-local data/extensions container.
2019-03-29 23:29:11 +00:00
#[inline]
2019-12-07 18:46:51 +00:00
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.extensions.borrow_mut()
2019-03-29 23:29:11 +00:00
}
/// Returns a reference to the body of this response.
2018-01-01 01:26:32 +00:00
#[inline]
pub fn body(&self) -> &B {
2019-02-08 05:16:46 +00:00
&self.body
2017-10-07 04:48:14 +00:00
}
/// Sets new body.
#[inline]
pub fn set_body<B2>(self, body: B2) -> Response<B2> {
2019-02-08 05:16:46 +00:00
Response {
head: self.head,
body,
extensions: self.extensions,
2019-02-08 05:16:46 +00:00
}
2017-10-08 04:48:00 +00:00
}
/// Drops body and returns new response.
#[inline]
pub fn drop_body(self) -> Response<()> {
self.set_body(())
}
/// Sets new body, returning new response and previous body value.
#[inline]
pub(crate) fn replace_body<B2>(self, body: B2) -> (Response<B2>, B) {
2019-02-08 05:16:46 +00:00
(
Response {
head: self.head,
body,
extensions: self.extensions,
2019-02-08 05:16:46 +00:00
},
self.body,
)
2018-06-25 04:10:02 +00:00
}
2019-02-19 01:01:35 +00:00
/// Returns split head and body.
///
/// # Implementation Notes
2021-12-17 19:35:08 +00:00
/// Due to internal performance optimizations, the first element of the returned tuple is a
/// `Response` as well but only contains the head of the response this was called on.
#[inline]
pub fn into_parts(self) -> (Response<()>, B) {
self.replace_body(())
}
2022-01-23 23:26:35 +00:00
/// Map the current body type to another using a closure, returning a new response.
///
/// Closure receives the response head and the current body type.
#[inline]
pub fn map_body<F, B2>(mut self, f: F) -> Response<B2>
2019-02-19 01:01:35 +00:00
where
F: FnOnce(&mut ResponseHead, B) -> B2,
2019-02-19 01:01:35 +00:00
{
let body = f(&mut self.head, self.body);
Response {
head: self.head,
body,
extensions: self.extensions,
2019-02-19 01:01:35 +00:00
}
}
2019-03-06 05:15:18 +00:00
2022-01-23 23:26:35 +00:00
/// Map the current body to a type-erased `BoxBody`.
2021-12-04 19:40:47 +00:00
#[inline]
pub fn map_into_boxed_body(self) -> Response<BoxBody>
where
B: MessageBody + 'static,
{
self.map_body(|_, body| body.boxed())
2021-12-04 19:40:47 +00:00
}
2022-01-23 23:26:35 +00:00
/// Returns the response body, dropping all other parts.
#[inline]
pub fn into_body(self) -> B {
self.body
2019-03-06 05:15:18 +00:00
}
2017-10-07 04:48:14 +00:00
}
2017-10-10 23:03:32 +00:00
impl<B> fmt::Debug for Response<B>
where
B: MessageBody,
{
2019-12-07 18:46:51 +00:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-04-13 23:02:01 +00:00
let res = writeln!(
f,
2018-10-05 18:04:59 +00:00
"\nResponse {:?} {}{}",
2019-02-08 05:16:46 +00:00
self.head.version,
self.head.status,
self.head.reason.unwrap_or(""),
2018-04-13 23:02:01 +00:00
);
2018-04-09 21:25:30 +00:00
let _ = writeln!(f, " headers:");
2019-02-08 05:16:46 +00:00
for (key, val) in self.head.headers.iter() {
2018-04-09 21:25:30 +00:00
let _ = writeln!(f, " {:?}: {:?}", key, val);
2017-11-09 03:31:25 +00:00
}
let _ = writeln!(f, " body: {:?}", self.body.size());
2017-11-09 03:31:25 +00:00
res
}
}
impl<B: Default> Default for Response<B> {
#[inline]
fn default() -> Response<B> {
Response::with_body(StatusCode::default(), B::default())
2019-11-21 15:34:04 +00:00
}
}
2021-12-08 06:01:11 +00:00
impl<I: Into<Response<BoxBody>>, E: Into<Error>> From<Result<I, E>> for Response<BoxBody> {
2017-11-28 21:52:53 +00:00
fn from(res: Result<I, E>) -> Self {
match res {
Ok(val) => val.into(),
2021-12-04 19:40:47 +00:00
Err(err) => Response::from(err.into()),
2017-11-28 21:52:53 +00:00
}
}
}
impl From<ResponseBuilder> for Response<EitherBody<()>> {
2018-10-05 18:04:59 +00:00
fn from(mut builder: ResponseBuilder) -> Self {
builder.finish()
2017-11-29 17:17:00 +00:00
}
}
2021-12-04 19:40:47 +00:00
impl From<std::convert::Infallible> for Response<BoxBody> {
2021-06-17 16:57:58 +00:00
fn from(val: std::convert::Infallible) -> Self {
match val {}
}
}
2021-12-04 19:40:47 +00:00
impl From<&'static str> for Response<&'static str> {
2017-11-29 17:17:00 +00:00
fn from(val: &'static str) -> Self {
2021-12-04 19:40:47 +00:00
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
2017-11-28 21:52:53 +00:00
}
}
2021-12-04 19:40:47 +00:00
impl From<&'static [u8]> for Response<&'static [u8]> {
2017-11-29 17:17:00 +00:00
fn from(val: &'static [u8]) -> Self {
2021-12-04 19:40:47 +00:00
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
2017-11-28 21:52:53 +00:00
}
}
2022-02-04 20:37:33 +00:00
impl From<Vec<u8>> for Response<Vec<u8>> {
fn from(val: Vec<u8>) -> Self {
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
impl From<&Vec<u8>> for Response<Vec<u8>> {
fn from(val: &Vec<u8>) -> Self {
let mut res = Response::with_body(StatusCode::OK, val.clone());
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
2021-12-04 19:40:47 +00:00
impl From<String> for Response<String> {
2017-11-29 17:17:00 +00:00
fn from(val: String) -> Self {
2021-12-04 19:40:47 +00:00
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
2017-11-28 21:52:53 +00:00
}
}
2021-12-04 19:40:47 +00:00
impl From<&String> for Response<String> {
fn from(val: &String) -> Self {
let mut res = Response::with_body(StatusCode::OK, val.clone());
let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
2021-12-04 19:40:47 +00:00
impl From<Bytes> for Response<Bytes> {
2017-11-29 17:17:00 +00:00
fn from(val: Bytes) -> Self {
2021-12-04 19:40:47 +00:00
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
2017-11-28 21:52:53 +00:00
}
}
2021-12-04 19:40:47 +00:00
impl From<BytesMut> for Response<BytesMut> {
2017-11-29 17:17:00 +00:00
fn from(val: BytesMut) -> Self {
2021-12-04 19:40:47 +00:00
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::APPLICATION_OCTET_STREAM.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
}
}
impl From<ByteString> for Response<ByteString> {
fn from(val: ByteString) -> Self {
let mut res = Response::with_body(StatusCode::OK, val);
let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap();
res.headers_mut().insert(header::CONTENT_TYPE, mime);
res
2017-11-28 21:52:53 +00:00
}
}
2017-10-23 05:54:11 +00:00
#[cfg(test)]
mod tests {
use super::*;
2021-12-04 19:40:47 +00:00
use crate::{
body::to_bytes,
header::{HeaderValue, CONTENT_TYPE, COOKIE},
2021-12-04 19:40:47 +00:00
};
2018-06-25 04:58:04 +00:00
2017-12-13 19:16:26 +00:00
#[test]
fn test_debug() {
let resp = Response::build(StatusCode::OK)
2021-01-15 02:11:10 +00:00
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
2017-12-13 19:16:26 +00:00
let dbg = format!("{:?}", resp);
2018-10-05 18:04:59 +00:00
assert!(dbg.contains("Response"));
2017-12-13 19:16:26 +00:00
}
2021-12-04 19:40:47 +00:00
#[actix_rt::test]
async fn test_into_response() {
let res = Response::from("test");
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("text/plain; charset=utf-8")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2017-11-28 21:52:53 +00:00
2021-12-04 19:40:47 +00:00
let res = Response::from(b"test".as_ref());
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("application/octet-stream")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2017-11-28 21:52:53 +00:00
2021-12-04 19:40:47 +00:00
let res = Response::from("test".to_owned());
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("text/plain; charset=utf-8")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2018-04-13 23:02:01 +00:00
2021-12-04 19:40:47 +00:00
let res = Response::from("test".to_owned());
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("text/plain; charset=utf-8")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2018-04-13 23:02:01 +00:00
2017-11-28 21:52:53 +00:00
let b = Bytes::from_static(b"test");
2021-12-04 19:40:47 +00:00
let res = Response::from(b);
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("application/octet-stream")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2017-11-28 21:52:53 +00:00
let b = Bytes::from_static(b"test");
2021-12-04 19:40:47 +00:00
let res = Response::from(b);
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("application/octet-stream")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
let b = BytesMut::from("test");
2021-12-04 19:40:47 +00:00
let res = Response::from(b);
assert_eq!(res.status(), StatusCode::OK);
2018-04-13 23:02:01 +00:00
assert_eq!(
2021-12-04 19:40:47 +00:00
res.headers().get(CONTENT_TYPE).unwrap(),
2018-04-13 23:02:01 +00:00
HeaderValue::from_static("application/octet-stream")
);
2021-12-04 19:40:47 +00:00
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(to_bytes(res.into_body()).await.unwrap(), &b"test"[..]);
2017-11-28 21:52:53 +00:00
}
2017-10-23 05:54:11 +00:00
}