1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-01-19 22:24:40 +01:00
actix-web/actix-http/src/response.rs

382 lines
10 KiB
Rust
Raw Normal View History

2021-04-14 02:12:47 +01:00
//! HTTP response.
2021-01-15 02:11:10 +00:00
use std::{
cell::{Ref, RefMut},
fmt, str,
2021-01-15 02:11:10 +00:00
};
2017-10-06 21:48:14 -07:00
2019-12-05 23:35:43 +06:00
use bytes::{Bytes, BytesMut};
2017-12-07 16:40:29 -08:00
2021-02-13 15:08:43 +00:00
use crate::{
2021-06-17 17:57:58 +01:00
body::{AnyBody, MessageBody},
error::Error,
extensions::Extensions,
2021-04-14 02:12:47 +01:00
http::{HeaderMap, StatusCode},
message::{BoxedResponseHead, ResponseHead},
ResponseBuilder,
2021-02-13 15:08:43 +00:00
};
2018-03-09 10:00:15 -08:00
2021-04-14 02:12:47 +01:00
/// An HTTP response.
2021-04-13 11:16:12 +01:00
pub struct Response<B> {
2021-04-14 02:12:47 +01:00
pub(crate) head: BoxedResponseHead,
pub(crate) body: B,
2019-02-07 21:16:46 -08:00
}
2017-12-15 16:24:15 -08:00
2021-06-17 17:57:58 +01:00
impl Response<AnyBody> {
/// Constructs a new response with default body.
#[inline]
2021-06-17 17:57:58 +01:00
pub fn new(status: StatusCode) -> Self {
Response {
head: BoxedResponseHead::new(status),
body: AnyBody::empty(),
}
}
/// Constructs a new response builder.
2017-10-10 16:03:32 -07:00
#[inline]
2018-10-05 11:04:59 -07:00
pub fn build(status: StatusCode) -> ResponseBuilder {
2019-02-07 21:16:46 -08:00
ResponseBuilder::new(status)
2017-10-10 16:03:32 -07: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 17:57:58 +01:00
pub fn ok() -> Self {
Response::new(StatusCode::OK)
}
/// Constructs a new response with status 400 Bad Request.
2017-10-06 21:48:14 -07:00
#[inline]
2021-06-17 17:57:58 +01:00
pub fn bad_request() -> Self {
Response::new(StatusCode::BAD_REQUEST)
}
/// Constructs a new response with status 404 Not Found.
#[inline]
2021-06-17 17:57:58 +01:00
pub fn not_found() -> Self {
Response::new(StatusCode::NOT_FOUND)
2017-10-06 21:48:14 -07:00
}
/// Constructs a new response with status 500 Internal Server Error.
#[inline]
2021-06-17 17:57:58 +01:00
pub fn internal_server_error() -> Self {
Response::new(StatusCode::INTERNAL_SERVER_ERROR)
}
// end shortcuts
2018-11-17 20:21:28 -08:00
}
2019-02-20 21:05:37 -08: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 09:13:33 +09:00
body,
}
}
/// Returns a reference to the head of this response.
2018-11-17 20:21:28 -08:00
#[inline]
2018-11-19 14:57:12 -08:00
pub fn head(&self) -> &ResponseHead {
2019-02-07 21:16:46 -08:00
&*self.head
2018-11-19 14:57:12 -08:00
}
/// Returns a mutable reference to the head of this response.
2018-11-19 14:57:12 -08:00
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
2019-02-07 21:16:46 -08:00
&mut *self.head
2018-11-17 20:21:28 -08:00
}
/// Returns the status code of this response.
2018-11-17 20:21:28 -08:00
#[inline]
pub fn status(&self) -> StatusCode {
2019-02-07 21:16:46 -08:00
self.head.status
2018-11-17 20:21:28 -08:00
}
/// Returns a mutable reference the status code of this response.
2018-11-17 20:21:28 -08:00
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
2019-02-07 21:16:46 -08:00
&mut self.head.status
2018-11-17 20:21:28 -08:00
}
/// Returns a reference to response headers.
2017-10-06 21:48:14 -07:00
#[inline]
2017-10-09 23:07:32 -07:00
pub fn headers(&self) -> &HeaderMap {
2019-02-07 21:16:46 -08:00
&self.head.headers
2017-10-06 21:48:14 -07:00
}
/// Returns a mutable reference to response headers.
2017-10-06 21:48:14 -07:00
#[inline]
2017-10-09 23:07:32 -07:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2019-02-07 21:16:46 -08:00
&mut self.head.headers
2017-10-06 21:48:14 -07:00
}
/// Returns true if connection upgrade is enabled.
2017-12-31 17:26:32 -08:00
#[inline]
2017-10-07 21:48:00 -07:00
pub fn upgrade(&self) -> bool {
2019-02-07 21:16:46 -08:00
self.head.upgrade()
2017-10-07 21:48:00 -07:00
}
/// Returns true if keep-alive is enabled.
2018-11-18 17:52:56 -08:00
pub fn keep_alive(&self) -> bool {
2019-02-07 21:16:46 -08:00
self.head.keep_alive()
2017-10-06 21:48:14 -07:00
}
2017-10-07 21:48:00 -07:00
/// Returns a reference to the extensions of this response.
2019-03-30 02:29:11 +03:00
#[inline]
2019-12-08 00:46:51 +06:00
pub fn extensions(&self) -> Ref<'_, Extensions> {
2019-03-30 02:29:11 +03:00
self.head.extensions.borrow()
}
/// Returns a mutable reference to the extensions of this response.
2019-03-30 02:29:11 +03:00
#[inline]
2019-12-08 00:46:51 +06:00
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
2019-03-30 02:29:11 +03:00
self.head.extensions.borrow_mut()
}
/// Returns a reference to the body of this response.
2017-12-31 17:26:32 -08:00
#[inline]
pub fn body(&self) -> &B {
2019-02-07 21:16:46 -08:00
&self.body
2017-10-06 21:48:14 -07:00
}
/// Sets new body.
pub fn set_body<B2>(self, body: B2) -> Response<B2> {
2019-02-07 21:16:46 -08:00
Response {
head: self.head,
body,
2019-02-07 21:16:46 -08:00
}
2017-10-07 21:48:00 -07:00
}
/// Drops body and returns new response.
pub fn drop_body(self) -> Response<()> {
self.set_body(())
}
/// Sets new body, returning new response and previous body value.
pub(crate) fn replace_body<B2>(self, body: B2) -> (Response<B2>, B) {
2019-02-07 21:16:46 -08:00
(
Response {
head: self.head,
body,
2019-02-07 21:16:46 -08:00
},
self.body,
)
2018-06-25 10:10:02 +06:00
}
2019-02-18 17:01:35 -08:00
/// Returns split head and body.
///
/// # Implementation Notes
/// Due to internal performance optimisations, the first element of the returned tuple is a
/// `Response` as well but only contains the head of the response this was called on.
pub fn into_parts(self) -> (Response<()>, B) {
self.replace_body(())
}
/// Returns new response with mapped body.
pub fn map_body<F, B2>(mut self, f: F) -> Response<B2>
2019-02-18 17:01:35 -08:00
where
F: FnOnce(&mut ResponseHead, B) -> B2,
2019-02-18 17:01:35 -08:00
{
let body = f(&mut self.head, self.body);
Response {
head: self.head,
body,
2019-02-18 17:01:35 -08:00
}
}
2019-03-05 21:15:18 -08:00
/// Returns body, consuming this response.
pub fn into_body(self) -> B {
self.body
2019-03-05 21:15:18 -08:00
}
2017-10-06 21:48:14 -07:00
}
2017-10-10 16:03:32 -07:00
impl<B> fmt::Debug for Response<B>
where
B: MessageBody,
{
2019-12-08 00:46:51 +06:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2018-04-13 16:02:01 -07:00
let res = writeln!(
f,
2018-10-05 11:04:59 -07:00
"\nResponse {:?} {}{}",
2019-02-07 21:16:46 -08:00
self.head.version,
self.head.status,
self.head.reason.unwrap_or(""),
2018-04-13 16:02:01 -07:00
);
2018-04-09 14:25:30 -07:00
let _ = writeln!(f, " headers:");
2019-02-07 21:16:46 -08:00
for (key, val) in self.head.headers.iter() {
2018-04-09 14:25:30 -07:00
let _ = writeln!(f, " {:?}: {:?}", key, val);
2017-11-08 19:31:25 -08:00
}
let _ = writeln!(f, " body: {:?}", self.body.size());
2017-11-08 19:31:25 -08:00
res
}
}
impl<B: Default> Default for Response<B> {
#[inline]
fn default() -> Response<B> {
Response::with_body(StatusCode::default(), B::default())
2019-11-21 21:34:04 +06:00
}
}
2021-06-17 17:57:58 +01:00
impl<I: Into<Response<AnyBody>>, E: Into<Error>> From<Result<I, E>>
for Response<AnyBody>
{
2017-11-28 13:52:53 -08:00
fn from(res: Result<I, E>) -> Self {
match res {
Ok(val) => val.into(),
Err(err) => err.into().into(),
}
}
}
2021-06-17 17:57:58 +01:00
impl From<ResponseBuilder> for Response<AnyBody> {
2018-10-05 11:04:59 -07:00
fn from(mut builder: ResponseBuilder) -> Self {
builder.finish()
2017-11-29 09:17:00 -08:00
}
}
2021-06-17 17:57:58 +01:00
impl From<std::convert::Infallible> for Response<AnyBody> {
fn from(val: std::convert::Infallible) -> Self {
match val {}
}
}
impl From<&'static str> for Response<AnyBody> {
2017-11-29 09:17:00 -08:00
fn from(val: &'static str) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
2018-04-29 09:09:08 -07:00
.body(val)
2017-11-28 13:52:53 -08:00
}
}
2021-06-17 17:57:58 +01:00
impl From<&'static [u8]> for Response<AnyBody> {
2017-11-29 09:17:00 -08:00
fn from(val: &'static [u8]) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
2018-04-29 09:09:08 -07:00
.body(val)
2017-11-28 13:52:53 -08:00
}
}
2021-06-17 17:57:58 +01:00
impl From<String> for Response<AnyBody> {
2017-11-29 09:17:00 -08:00
fn from(val: String) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
2018-04-29 09:09:08 -07:00
.body(val)
2017-11-28 13:52:53 -08:00
}
}
2021-06-17 17:57:58 +01:00
impl<'a> From<&'a String> for Response<AnyBody> {
fn from(val: &'a String) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::TEXT_PLAIN_UTF_8)
.body(val)
}
}
2021-06-17 17:57:58 +01:00
impl From<Bytes> for Response<AnyBody> {
2017-11-29 09:17:00 -08:00
fn from(val: Bytes) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
2018-04-29 09:09:08 -07:00
.body(val)
2017-11-28 13:52:53 -08:00
}
}
2021-06-17 17:57:58 +01:00
impl From<BytesMut> for Response<AnyBody> {
2017-11-29 09:17:00 -08:00
fn from(val: BytesMut) -> Self {
Response::build(StatusCode::OK)
.content_type(mime::APPLICATION_OCTET_STREAM)
2018-04-29 09:09:08 -07:00
.body(val)
2017-11-28 13:52:53 -08:00
}
}
2017-10-22 22:54:11 -07:00
#[cfg(test)]
mod tests {
use super::*;
2021-04-14 02:12:47 +01:00
use crate::http::header::{HeaderValue, CONTENT_TYPE, COOKIE};
2018-06-25 10:58:04 +06:00
2017-12-13 11:16:26 -08: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 11:16:26 -08:00
let dbg = format!("{:?}", resp);
2018-10-05 11:04:59 -07:00
assert!(dbg.contains("Response"));
2017-12-13 11:16:26 -08:00
}
2017-11-28 13:52:53 -08:00
#[test]
fn test_into_response() {
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = "test".into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 13:52:53 -08:00
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = b"test".as_ref().into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 13:52:53 -08:00
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = "test".to_owned().into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2018-04-13 16:02:01 -07:00
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = (&"test".to_owned()).into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("text/plain; charset=utf-8")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2018-04-13 16:02:01 -07:00
2017-11-28 13:52:53 -08:00
let b = Bytes::from_static(b"test");
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = b.into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
2017-11-28 13:52:53 -08:00
let b = Bytes::from_static(b"test");
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = b.into();
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07:00
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),
HeaderValue::from_static("application/octet-stream")
);
2017-11-28 13:52:53 -08:00
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().get_ref(), b"test");
let b = BytesMut::from("test");
2021-06-17 17:57:58 +01:00
let resp: Response<AnyBody> = b.into();
assert_eq!(resp.status(), StatusCode::OK);
2018-04-13 16:02:01 -07: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 13:52:53 -08:00
}
2017-10-22 22:54:11 -07:00
}