1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-01 16:55:08 +02:00

remove http-codes builders from actix-http (#2159)

This commit is contained in:
Rob Ede
2021-04-14 02:00:14 +01:00
committed by GitHub
parent 02ced426fd
commit 23e0c9b6e0
21 changed files with 539 additions and 573 deletions

View File

@ -1,20 +1,23 @@
use std::cell::RefCell;
use std::rc::Rc;
use actix_http::{Extensions, Request, Response};
use actix_http::{Extensions, Request};
use actix_router::{Path, ResourceDef, Router, Url};
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{fn_service, Service, ServiceFactory};
use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all;
use crate::config::{AppConfig, AppService};
use crate::data::FnDataFactory;
use crate::error::Error;
use crate::guard::Guard;
use crate::request::{HttpRequest, HttpRequestPool};
use crate::rmap::ResourceMap;
use crate::service::{AppServiceFactory, ServiceRequest, ServiceResponse};
use crate::{
config::{AppConfig, AppService},
HttpResponse,
};
type Guards = Vec<Box<dyn Guard>>;
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
@ -64,7 +67,7 @@ where
// if no user defined default service exists.
let default = self.default.clone().unwrap_or_else(|| {
Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async {
Ok(req.into_response(Response::NotFound().finish()))
Ok(req.into_response(HttpResponse::NotFound()))
})))
});

View File

@ -3,7 +3,7 @@ use std::fmt;
use std::future::Future;
use std::rc::Rc;
use actix_http::{Error, Extensions, Response};
use actix_http::{Error, Extensions};
use actix_router::IntoPattern;
use actix_service::boxed::{self, BoxService, BoxServiceFactory};
use actix_service::{
@ -13,7 +13,6 @@ use actix_service::{
use futures_core::future::LocalBoxFuture;
use futures_util::future::join_all;
use crate::data::Data;
use crate::dev::{insert_slash, AppService, HttpServiceFactory, ResourceDef};
use crate::extract::FromRequest;
use crate::guard::Guard;
@ -21,6 +20,7 @@ use crate::handler::Handler;
use crate::responder::Responder;
use crate::route::{Route, RouteService};
use crate::service::{ServiceRequest, ServiceResponse};
use crate::{data::Data, HttpResponse};
type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>;
type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>;
@ -71,7 +71,7 @@ impl Resource {
guards: Vec::new(),
app_data: None,
default: boxed::factory(fn_service(|req: ServiceRequest| async {
Ok(req.into_response(Response::MethodNotAllowed().finish()))
Ok(req.into_response(HttpResponse::MethodNotAllowed()))
})),
}
}

View File

@ -1,17 +1,15 @@
use std::{
cell::{Ref, RefMut},
convert::TryInto,
fmt,
future::Future,
mem,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{
body::{Body, BodyStream, MessageBody, ResponseBody},
body::{Body, BodyStream},
http::{
header::{self, HeaderMap, HeaderName, IntoHeaderPair, IntoHeaderValue},
header::{self, HeaderName, IntoHeaderPair, IntoHeaderValue},
ConnectionType, Error as HttpError, StatusCode,
},
Extensions, Response, ResponseHead,
@ -25,282 +23,10 @@ use actix_http::http::header::HeaderValue;
#[cfg(feature = "cookies")]
use cookie::{Cookie, CookieJar};
use crate::error::{Error, JsonPayloadError};
/// An HTTP Response
pub struct HttpResponse<B = Body> {
res: Response<B>,
error: Option<Error>,
}
impl HttpResponse<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> HttpResponseBuilder {
HttpResponseBuilder::new(status)
}
/// Create HTTP response builder
#[inline]
pub fn build_from<T: Into<HttpResponseBuilder>>(source: T) -> HttpResponseBuilder {
source.into()
}
/// Create a response.
#[inline]
pub fn new(status: StatusCode) -> Self {
Self {
res: Response::new(status),
error: None,
}
}
/// Create an error response.
#[inline]
pub fn from_error(error: Error) -> Self {
let res = error.as_response_error().error_response();
Self {
res,
error: Some(error),
}
}
/// Convert response to response with body
pub fn into_body<B>(self) -> HttpResponse<B> {
HttpResponse {
res: self.res.into_body(),
error: self.error,
}
}
}
impl<B> HttpResponse<B> {
/// Constructs a response with body
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Self {
Self {
res: Response::with_body(status, body),
error: None,
}
}
/// Returns a reference to response head.
#[inline]
pub fn head(&self) -> &ResponseHead {
self.res.head()
}
/// Returns a mutable reference to response head.
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
self.res.head_mut()
}
/// The source `error` for this response
#[inline]
pub fn error(&self) -> Option<&Error> {
self.error.as_ref()
}
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
self.res.status()
}
/// Set the `StatusCode` for this response
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
self.res.status_mut()
}
/// Get the headers from the response
#[inline]
pub fn headers(&self) -> &HeaderMap {
self.res.headers()
}
/// Get a mutable reference to the headers
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.res.headers_mut()
}
/// Get an iterator for the cookies set by this response.
#[cfg(feature = "cookies")]
pub fn cookies(&self) -> CookieIter<'_> {
CookieIter {
iter: self.headers().get_all(header::SET_COOKIE),
}
}
/// Add a cookie to this response
#[cfg(feature = "cookies")]
pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
HeaderValue::from_str(&cookie.to_string())
.map(|c| {
self.headers_mut().append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}
/// Remove all cookies with the given name from this response. Returns
/// the number of cookies removed.
#[cfg(feature = "cookies")]
pub fn del_cookie(&mut self, name: &str) -> usize {
let headers = self.headers_mut();
let vals: Vec<HeaderValue> = headers
.get_all(header::SET_COOKIE)
.map(|v| v.to_owned())
.collect();
headers.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) {
if c.name() == name {
count += 1;
continue;
}
}
}
// put set-cookie header head back if it does not validate
headers.append(header::SET_COOKIE, v);
}
count
}
/// Connection upgrade status
#[inline]
pub fn upgrade(&self) -> bool {
self.res.upgrade()
}
/// Keep-alive status for this connection
pub fn keep_alive(&self) -> bool {
self.res.keep_alive()
}
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> {
self.res.extensions()
}
/// Mutable reference to a the response's extensions
#[inline]
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.res.extensions_mut()
}
/// Get body of this response
#[inline]
pub fn body(&self) -> &ResponseBody<B> {
self.res.body()
}
/// Set a body
pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
HttpResponse {
res: self.res.set_body(body),
error: None,
// error: self.error, ??
}
}
/// Split response and body
pub fn into_parts(self) -> (HttpResponse<()>, ResponseBody<B>) {
let (head, body) = self.res.into_parts();
(
HttpResponse {
res: head,
error: None,
},
body,
)
}
/// Drop request's body
pub fn drop_body(self) -> HttpResponse<()> {
HttpResponse {
res: self.res.drop_body(),
error: None,
}
}
/// Set a body and return previous body value
pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
HttpResponse {
res: self.res.map_body(f),
error: self.error,
}
}
/// Extract response body
pub fn take_body(&mut self) -> ResponseBody<B> {
self.res.take_body()
}
}
impl<B: MessageBody> fmt::Debug for HttpResponse<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse")
.field("error", &self.error)
.field("res", &self.res)
.finish()
}
}
impl<B> From<Response<B>> for HttpResponse<B> {
fn from(res: Response<B>) -> Self {
HttpResponse { res, error: None }
}
}
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
HttpResponse::from_error(err)
}
}
impl<B> From<HttpResponse<B>> for Response<B> {
fn from(res: HttpResponse<B>) -> Self {
// this impl will always be called as part of dispatcher
// TODO: expose cause somewhere?
// if let Some(err) = res.error {
// eprintln!("impl<B> From<HttpResponse<B>> for Response<B> let Some(err)");
// return Response::from_error(err).into_body();
// }
res.res
}
}
impl Future for HttpResponse {
type Output = Result<Response<Body>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {
return Poll::Ready(Ok(Response::from_error(err).into_body()));
}
Poll::Ready(Ok(mem::replace(
&mut self.res,
Response::new(StatusCode::default()),
)))
}
}
use crate::{
error::{Error, JsonPayloadError},
HttpResponse,
};
/// An HTTP response builder.
///
@ -695,146 +421,18 @@ impl Future for HttpResponseBuilder {
}
}
#[cfg(feature = "cookies")]
pub struct CookieIter<'a> {
iter: header::GetAll<'a>,
}
#[cfg(feature = "cookies")]
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()?) {
return Some(c);
}
}
None
}
}
mod http_codes {
//! Status code based HTTP response builders.
use actix_http::http::StatusCode;
use super::{HttpResponse, HttpResponseBuilder};
macro_rules! static_resp {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> HttpResponseBuilder {
HttpResponseBuilder::new($status)
}
};
}
impl HttpResponse {
static_resp!(Continue, StatusCode::CONTINUE);
static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS);
static_resp!(Processing, StatusCode::PROCESSING);
static_resp!(Ok, StatusCode::OK);
static_resp!(Created, StatusCode::CREATED);
static_resp!(Accepted, StatusCode::ACCEPTED);
static_resp!(
NonAuthoritativeInformation,
StatusCode::NON_AUTHORITATIVE_INFORMATION
);
static_resp!(NoContent, StatusCode::NO_CONTENT);
static_resp!(ResetContent, StatusCode::RESET_CONTENT);
static_resp!(PartialContent, StatusCode::PARTIAL_CONTENT);
static_resp!(MultiStatus, StatusCode::MULTI_STATUS);
static_resp!(AlreadyReported, StatusCode::ALREADY_REPORTED);
static_resp!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
static_resp!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
static_resp!(Found, StatusCode::FOUND);
static_resp!(SeeOther, StatusCode::SEE_OTHER);
static_resp!(NotModified, StatusCode::NOT_MODIFIED);
static_resp!(UseProxy, StatusCode::USE_PROXY);
static_resp!(TemporaryRedirect, StatusCode::TEMPORARY_REDIRECT);
static_resp!(PermanentRedirect, StatusCode::PERMANENT_REDIRECT);
static_resp!(BadRequest, StatusCode::BAD_REQUEST);
static_resp!(NotFound, StatusCode::NOT_FOUND);
static_resp!(Unauthorized, StatusCode::UNAUTHORIZED);
static_resp!(PaymentRequired, StatusCode::PAYMENT_REQUIRED);
static_resp!(Forbidden, StatusCode::FORBIDDEN);
static_resp!(MethodNotAllowed, StatusCode::METHOD_NOT_ALLOWED);
static_resp!(NotAcceptable, StatusCode::NOT_ACCEPTABLE);
static_resp!(
ProxyAuthenticationRequired,
StatusCode::PROXY_AUTHENTICATION_REQUIRED
);
static_resp!(RequestTimeout, StatusCode::REQUEST_TIMEOUT);
static_resp!(Conflict, StatusCode::CONFLICT);
static_resp!(Gone, StatusCode::GONE);
static_resp!(LengthRequired, StatusCode::LENGTH_REQUIRED);
static_resp!(PreconditionFailed, StatusCode::PRECONDITION_FAILED);
static_resp!(PreconditionRequired, StatusCode::PRECONDITION_REQUIRED);
static_resp!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE);
static_resp!(UriTooLong, StatusCode::URI_TOO_LONG);
static_resp!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE);
static_resp!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
static_resp!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
static_resp!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
static_resp!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
static_resp!(
RequestHeaderFieldsTooLarge,
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
);
static_resp!(
UnavailableForLegalReasons,
StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS
);
static_resp!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
static_resp!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
static_resp!(BadGateway, StatusCode::BAD_GATEWAY);
static_resp!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE);
static_resp!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT);
static_resp!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED);
static_resp!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES);
static_resp!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE);
static_resp!(LoopDetected, StatusCode::LOOP_DETECTED);
}
#[cfg(test)]
mod tests {
use crate::dev::Body;
use crate::http::StatusCode;
use crate::HttpResponse;
#[test]
fn test_build() {
let resp = HttpResponse::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK);
}
}
}
#[cfg(test)]
mod tests {
use bytes::{Bytes, BytesMut};
use actix_http::body;
use super::{HttpResponse, HttpResponseBuilder};
use crate::dev::{Body, MessageBody, ResponseBody};
use crate::http::header::{self, HeaderValue, CONTENT_TYPE, COOKIE};
use crate::http::StatusCode;
#[test]
fn test_debug() {
let resp = HttpResponse::Ok()
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse"));
}
use super::*;
use crate::{
dev::Body,
http::{
header::{self, HeaderValue, CONTENT_TYPE},
StatusCode,
},
};
#[test]
fn test_basic_builder() {
@ -872,26 +470,13 @@ mod tests {
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
}
pub async fn read_body<B>(mut body: ResponseBody<B>) -> Bytes
where
B: MessageBody + Unpin,
{
use futures_util::StreamExt as _;
let mut bytes = BytesMut::new();
while let Some(item) = body.next().await {
bytes.extend_from_slice(&item.unwrap());
}
bytes.freeze()
}
#[actix_rt::test]
async fn test_json() {
let mut resp = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]);
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!(
read_body(resp.take_body()).await.as_ref(),
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"#
);
@ -899,7 +484,7 @@ mod tests {
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("application/json"));
assert_eq!(
read_body(resp.take_body()).await.as_ref(),
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"#
);
@ -910,7 +495,7 @@ mod tests {
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
assert_eq!(ct, HeaderValue::from_static("text/json"));
assert_eq!(
read_body(resp.take_body()).await.as_ref(),
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"["v1","v2","v3"]"#
);
}
@ -922,7 +507,7 @@ mod tests {
);
assert_eq!(
read_body(resp.take_body()).await.as_ref(),
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
br#"{"test-key":"test-value"}"#
);
}

View File

@ -0,0 +1,99 @@
//! Status code based HTTP response builders.
use actix_http::http::StatusCode;
use crate::{HttpResponse, HttpResponseBuilder};
macro_rules! static_resp {
($name:ident, $status:expr) => {
#[allow(non_snake_case, missing_docs)]
pub fn $name() -> HttpResponseBuilder {
HttpResponseBuilder::new($status)
}
};
}
impl HttpResponse {
static_resp!(Continue, StatusCode::CONTINUE);
static_resp!(SwitchingProtocols, StatusCode::SWITCHING_PROTOCOLS);
static_resp!(Processing, StatusCode::PROCESSING);
static_resp!(Ok, StatusCode::OK);
static_resp!(Created, StatusCode::CREATED);
static_resp!(Accepted, StatusCode::ACCEPTED);
static_resp!(
NonAuthoritativeInformation,
StatusCode::NON_AUTHORITATIVE_INFORMATION
);
static_resp!(NoContent, StatusCode::NO_CONTENT);
static_resp!(ResetContent, StatusCode::RESET_CONTENT);
static_resp!(PartialContent, StatusCode::PARTIAL_CONTENT);
static_resp!(MultiStatus, StatusCode::MULTI_STATUS);
static_resp!(AlreadyReported, StatusCode::ALREADY_REPORTED);
static_resp!(MultipleChoices, StatusCode::MULTIPLE_CHOICES);
static_resp!(MovedPermanently, StatusCode::MOVED_PERMANENTLY);
static_resp!(Found, StatusCode::FOUND);
static_resp!(SeeOther, StatusCode::SEE_OTHER);
static_resp!(NotModified, StatusCode::NOT_MODIFIED);
static_resp!(UseProxy, StatusCode::USE_PROXY);
static_resp!(TemporaryRedirect, StatusCode::TEMPORARY_REDIRECT);
static_resp!(PermanentRedirect, StatusCode::PERMANENT_REDIRECT);
static_resp!(BadRequest, StatusCode::BAD_REQUEST);
static_resp!(NotFound, StatusCode::NOT_FOUND);
static_resp!(Unauthorized, StatusCode::UNAUTHORIZED);
static_resp!(PaymentRequired, StatusCode::PAYMENT_REQUIRED);
static_resp!(Forbidden, StatusCode::FORBIDDEN);
static_resp!(MethodNotAllowed, StatusCode::METHOD_NOT_ALLOWED);
static_resp!(NotAcceptable, StatusCode::NOT_ACCEPTABLE);
static_resp!(
ProxyAuthenticationRequired,
StatusCode::PROXY_AUTHENTICATION_REQUIRED
);
static_resp!(RequestTimeout, StatusCode::REQUEST_TIMEOUT);
static_resp!(Conflict, StatusCode::CONFLICT);
static_resp!(Gone, StatusCode::GONE);
static_resp!(LengthRequired, StatusCode::LENGTH_REQUIRED);
static_resp!(PreconditionFailed, StatusCode::PRECONDITION_FAILED);
static_resp!(PreconditionRequired, StatusCode::PRECONDITION_REQUIRED);
static_resp!(PayloadTooLarge, StatusCode::PAYLOAD_TOO_LARGE);
static_resp!(UriTooLong, StatusCode::URI_TOO_LONG);
static_resp!(UnsupportedMediaType, StatusCode::UNSUPPORTED_MEDIA_TYPE);
static_resp!(RangeNotSatisfiable, StatusCode::RANGE_NOT_SATISFIABLE);
static_resp!(ExpectationFailed, StatusCode::EXPECTATION_FAILED);
static_resp!(UnprocessableEntity, StatusCode::UNPROCESSABLE_ENTITY);
static_resp!(TooManyRequests, StatusCode::TOO_MANY_REQUESTS);
static_resp!(
RequestHeaderFieldsTooLarge,
StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE
);
static_resp!(
UnavailableForLegalReasons,
StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS
);
static_resp!(InternalServerError, StatusCode::INTERNAL_SERVER_ERROR);
static_resp!(NotImplemented, StatusCode::NOT_IMPLEMENTED);
static_resp!(BadGateway, StatusCode::BAD_GATEWAY);
static_resp!(ServiceUnavailable, StatusCode::SERVICE_UNAVAILABLE);
static_resp!(GatewayTimeout, StatusCode::GATEWAY_TIMEOUT);
static_resp!(VersionNotSupported, StatusCode::HTTP_VERSION_NOT_SUPPORTED);
static_resp!(VariantAlsoNegotiates, StatusCode::VARIANT_ALSO_NEGOTIATES);
static_resp!(InsufficientStorage, StatusCode::INSUFFICIENT_STORAGE);
static_resp!(LoopDetected, StatusCode::LOOP_DETECTED);
}
#[cfg(test)]
mod tests {
use crate::dev::Body;
use crate::http::StatusCode;
use crate::HttpResponse;
#[test]
fn test_build() {
let resp = HttpResponse::Ok().body(Body::Empty);
assert_eq!(resp.status(), StatusCode::OK);
}
}

10
src/response/mod.rs Normal file
View File

@ -0,0 +1,10 @@
mod builder;
mod http_codes;
#[allow(clippy::module_inception)]
mod response;
pub use self::builder::HttpResponseBuilder;
pub use self::response::HttpResponse;
#[cfg(feature = "cookies")]
pub use self::response::CookieIter;

330
src/response/response.rs Normal file
View File

@ -0,0 +1,330 @@
use std::{
cell::{Ref, RefMut},
fmt,
future::Future,
mem,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{
body::{Body, MessageBody, ResponseBody},
http::{header::HeaderMap, StatusCode},
Extensions, Response, ResponseHead,
};
#[cfg(feature = "cookies")]
use {
actix_http::http::{
header::{self, HeaderValue},
Error as HttpError,
},
cookie::Cookie,
};
use crate::{error::Error, HttpResponseBuilder};
/// An HTTP Response
pub struct HttpResponse<B = Body> {
res: Response<B>,
error: Option<Error>,
}
impl HttpResponse<Body> {
/// Create HTTP response builder with specific status.
#[inline]
pub fn build(status: StatusCode) -> HttpResponseBuilder {
HttpResponseBuilder::new(status)
}
/// Create a response.
#[inline]
pub fn new(status: StatusCode) -> Self {
Self {
res: Response::new(status),
error: None,
}
}
/// Create an error response.
#[inline]
pub fn from_error(error: Error) -> Self {
let res = error.as_response_error().error_response();
Self {
res,
error: Some(error),
}
}
/// Convert response to response with body
pub fn into_body<B>(self) -> HttpResponse<B> {
HttpResponse {
res: self.res.into_body(),
error: self.error,
}
}
}
impl<B> HttpResponse<B> {
/// Constructs a response with body
#[inline]
pub fn with_body(status: StatusCode, body: B) -> Self {
Self {
res: Response::with_body(status, body),
error: None,
}
}
/// Returns a reference to response head.
#[inline]
pub fn head(&self) -> &ResponseHead {
self.res.head()
}
/// Returns a mutable reference to response head.
#[inline]
pub fn head_mut(&mut self) -> &mut ResponseHead {
self.res.head_mut()
}
/// The source `error` for this response
#[inline]
pub fn error(&self) -> Option<&Error> {
self.error.as_ref()
}
/// Get the response status code
#[inline]
pub fn status(&self) -> StatusCode {
self.res.status()
}
/// Set the `StatusCode` for this response
#[inline]
pub fn status_mut(&mut self) -> &mut StatusCode {
self.res.status_mut()
}
/// Get the headers from the response
#[inline]
pub fn headers(&self) -> &HeaderMap {
self.res.headers()
}
/// Get a mutable reference to the headers
#[inline]
pub fn headers_mut(&mut self) -> &mut HeaderMap {
self.res.headers_mut()
}
/// Get an iterator for the cookies set by this response.
#[cfg(feature = "cookies")]
pub fn cookies(&self) -> CookieIter<'_> {
CookieIter {
iter: self.headers().get_all(header::SET_COOKIE),
}
}
/// Add a cookie to this response
#[cfg(feature = "cookies")]
pub fn add_cookie(&mut self, cookie: &Cookie<'_>) -> Result<(), HttpError> {
HeaderValue::from_str(&cookie.to_string())
.map(|c| {
self.headers_mut().append(header::SET_COOKIE, c);
})
.map_err(|e| e.into())
}
/// Remove all cookies with the given name from this response. Returns
/// the number of cookies removed.
#[cfg(feature = "cookies")]
pub fn del_cookie(&mut self, name: &str) -> usize {
let headers = self.headers_mut();
let vals: Vec<HeaderValue> = headers
.get_all(header::SET_COOKIE)
.map(|v| v.to_owned())
.collect();
headers.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) {
if c.name() == name {
count += 1;
continue;
}
}
}
// put set-cookie header head back if it does not validate
headers.append(header::SET_COOKIE, v);
}
count
}
/// Connection upgrade status
#[inline]
pub fn upgrade(&self) -> bool {
self.res.upgrade()
}
/// Keep-alive status for this connection
pub fn keep_alive(&self) -> bool {
self.res.keep_alive()
}
/// Responses extensions
#[inline]
pub fn extensions(&self) -> Ref<'_, Extensions> {
self.res.extensions()
}
/// Mutable reference to a the response's extensions
#[inline]
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
self.res.extensions_mut()
}
/// Get body of this response
#[inline]
pub fn body(&self) -> &ResponseBody<B> {
self.res.body()
}
/// Set a body
pub fn set_body<B2>(self, body: B2) -> HttpResponse<B2> {
HttpResponse {
res: self.res.set_body(body),
error: None,
// error: self.error, ??
}
}
/// Split response and body
pub fn into_parts(self) -> (HttpResponse<()>, ResponseBody<B>) {
let (head, body) = self.res.into_parts();
(
HttpResponse {
res: head,
error: None,
},
body,
)
}
/// Drop request's body
pub fn drop_body(self) -> HttpResponse<()> {
HttpResponse {
res: self.res.drop_body(),
error: None,
}
}
/// Set a body and return previous body value
pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
where
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
{
HttpResponse {
res: self.res.map_body(f),
error: self.error,
}
}
/// Extract response body
pub fn take_body(&mut self) -> ResponseBody<B> {
self.res.take_body()
}
}
impl<B: MessageBody> fmt::Debug for HttpResponse<B> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HttpResponse")
.field("error", &self.error)
.field("res", &self.res)
.finish()
}
}
impl<B> From<Response<B>> for HttpResponse<B> {
fn from(res: Response<B>) -> Self {
HttpResponse { res, error: None }
}
}
impl From<Error> for HttpResponse {
fn from(err: Error) -> Self {
HttpResponse::from_error(err)
}
}
impl<B> From<HttpResponse<B>> for Response<B> {
fn from(res: HttpResponse<B>) -> Self {
// this impl will always be called as part of dispatcher
// TODO: expose cause somewhere?
// if let Some(err) = res.error {
// eprintln!("impl<B> From<HttpResponse<B>> for Response<B> let Some(err)");
// return Response::from_error(err).into_body();
// }
res.res
}
}
impl Future for HttpResponse {
type Output = Result<Response<Body>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {
return Poll::Ready(Ok(Response::from_error(err).into_body()));
}
Poll::Ready(Ok(mem::replace(
&mut self.res,
Response::new(StatusCode::default()),
)))
}
}
#[cfg(feature = "cookies")]
pub struct CookieIter<'a> {
iter: header::GetAll<'a>,
}
#[cfg(feature = "cookies")]
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()?) {
return Some(c);
}
}
None
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::http::header::{HeaderValue, COOKIE};
#[test]
fn test_debug() {
let resp = HttpResponse::Ok()
.append_header((COOKIE, HeaderValue::from_static("cookie1=value1; ")))
.append_header((COOKIE, HeaderValue::from_static("cookie2=value2; ")))
.finish();
let dbg = format!("{:?}", resp);
assert!(dbg.contains("HttpResponse"));
}
}