mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-02 01:05:08 +02:00
remove cookie support from -http (#2065)
This commit is contained in:
26
src/error.rs
26
src/error.rs
@ -5,7 +5,7 @@ use derive_more::{Display, Error, From};
|
||||
use serde_json::error::Error as JsonError;
|
||||
use url::ParseError as UrlParseError;
|
||||
|
||||
use crate::{http::StatusCode, HttpResponse};
|
||||
use crate::http::StatusCode;
|
||||
|
||||
/// Errors which can occur when attempting to generate resource uri.
|
||||
#[derive(Debug, PartialEq, Display, From)]
|
||||
@ -90,12 +90,11 @@ pub enum JsonPayloadError {
|
||||
|
||||
impl std::error::Error for JsonPayloadError {}
|
||||
|
||||
/// Return `BadRequest` for `JsonPayloadError`
|
||||
impl ResponseError for JsonPayloadError {
|
||||
fn error_response(&self) -> HttpResponse {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match *self {
|
||||
JsonPayloadError::Overflow => HttpResponse::new(StatusCode::PAYLOAD_TOO_LARGE),
|
||||
_ => HttpResponse::new(StatusCode::BAD_REQUEST),
|
||||
JsonPayloadError::Overflow => StatusCode::PAYLOAD_TOO_LARGE,
|
||||
_ => StatusCode::BAD_REQUEST,
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -168,26 +167,25 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_urlencoded_error() {
|
||||
let resp: HttpResponse =
|
||||
UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||
let resp = UrlencodedError::Overflow { size: 0, limit: 0 }.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||
let resp: HttpResponse = UrlencodedError::UnknownLength.error_response();
|
||||
let resp = UrlencodedError::UnknownLength.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED);
|
||||
let resp: HttpResponse = UrlencodedError::ContentType.error_response();
|
||||
let resp = UrlencodedError::ContentType.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_json_payload_error() {
|
||||
let resp: HttpResponse = JsonPayloadError::Overflow.error_response();
|
||||
let resp = JsonPayloadError::Overflow.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||
let resp: HttpResponse = JsonPayloadError::ContentType.error_response();
|
||||
let resp = JsonPayloadError::ContentType.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_query_payload_error() {
|
||||
let resp: HttpResponse = QueryPayloadError::Deserialize(
|
||||
let resp = QueryPayloadError::Deserialize(
|
||||
serde_urlencoded::from_str::<i32>("bad query").unwrap_err(),
|
||||
)
|
||||
.error_response();
|
||||
@ -196,9 +194,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_readlines_error() {
|
||||
let resp: HttpResponse = ReadlinesError::LimitOverflow.error_response();
|
||||
let resp = ReadlinesError::LimitOverflow.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
|
||||
let resp: HttpResponse = ReadlinesError::EncodingError.error_response();
|
||||
let resp = ReadlinesError::EncodingError.error_response();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
|
@ -3,20 +3,23 @@ use std::marker::PhantomData;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use actix_http::{Error, Response};
|
||||
use actix_http::Error;
|
||||
use actix_service::{Service, ServiceFactory};
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use futures_core::ready;
|
||||
use pin_project::pin_project;
|
||||
|
||||
use crate::extract::FromRequest;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::responder::Responder;
|
||||
use crate::service::{ServiceRequest, ServiceResponse};
|
||||
use crate::{
|
||||
extract::FromRequest,
|
||||
request::HttpRequest,
|
||||
responder::Responder,
|
||||
response::HttpResponse,
|
||||
service::{ServiceRequest, ServiceResponse},
|
||||
};
|
||||
|
||||
/// A request handler is an async function that accepts zero or more parameters that can be
|
||||
/// extracted from a request (ie, [`impl FromRequest`](crate::FromRequest)) and returns a type that can be converted into
|
||||
/// an [`HttpResponse`](crate::HttpResponse) (ie, [`impl Responder`](crate::Responder)).
|
||||
/// A request handler is an async function that accepts zero or more parameters that can be
|
||||
/// extracted from a request (i.e., [`impl FromRequest`](crate::FromRequest)) and returns a type
|
||||
/// that can be converted into an [`HttpResponse`] (that is, it impls the [`Responder`] trait).
|
||||
///
|
||||
/// If you got the error `the trait Handler<_, _, _> is not implemented`, then your function is not
|
||||
/// a valid handler. See [Request Handlers](https://actix.rs/docs/handlers/) for more information.
|
||||
@ -102,9 +105,7 @@ where
|
||||
type Error = Error;
|
||||
type Future = HandlerServiceFuture<F, T, R>;
|
||||
|
||||
fn poll_ready(&self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
actix_service::always_ready!();
|
||||
|
||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||
let (req, mut payload) = req.into_parts();
|
||||
@ -147,9 +148,9 @@ where
|
||||
let state = HandlerServiceFuture::Handle(fut, req.take());
|
||||
self.as_mut().set(state);
|
||||
}
|
||||
Err(e) => {
|
||||
let res: Response = e.into().into();
|
||||
Err(err) => {
|
||||
let req = req.take().unwrap();
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
|
||||
}
|
||||
};
|
||||
|
32
src/lib.rs
32
src/lib.rs
@ -86,6 +86,7 @@ mod request;
|
||||
mod request_data;
|
||||
mod resource;
|
||||
mod responder;
|
||||
mod response;
|
||||
mod rmap;
|
||||
mod route;
|
||||
mod scope;
|
||||
@ -95,19 +96,20 @@ pub mod test;
|
||||
pub(crate) mod types;
|
||||
pub mod web;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use actix_http::cookie;
|
||||
pub use actix_http::Response as HttpResponse;
|
||||
pub use actix_http::Response as BaseHttpResponse;
|
||||
pub use actix_http::{body, Error, HttpMessage, ResponseError, Result};
|
||||
#[doc(inline)]
|
||||
pub use actix_rt as rt;
|
||||
pub use actix_web_codegen::*;
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use cookie;
|
||||
|
||||
pub use crate::app::App;
|
||||
pub use crate::extract::FromRequest;
|
||||
pub use crate::request::HttpRequest;
|
||||
pub use crate::resource::Resource;
|
||||
pub use crate::responder::Responder;
|
||||
pub use crate::response::{HttpResponse, HttpResponseBuilder};
|
||||
pub use crate::route::Route;
|
||||
pub use crate::scope::Scope;
|
||||
pub use crate::server::HttpServer;
|
||||
@ -139,7 +141,7 @@ pub mod dev {
|
||||
pub use actix_http::body::{Body, BodySize, MessageBody, ResponseBody, SizedStream};
|
||||
#[cfg(feature = "compress")]
|
||||
pub use actix_http::encoding::Decoder as Decompress;
|
||||
pub use actix_http::ResponseBuilder as HttpResponseBuilder;
|
||||
pub use actix_http::ResponseBuilder as BaseHttpResponseBuilder;
|
||||
pub use actix_http::{Extensions, Payload, PayloadStream, RequestHead, ResponseHead};
|
||||
pub use actix_router::{Path, ResourceDef, ResourcePath, Url};
|
||||
pub use actix_server::Server;
|
||||
@ -189,4 +191,26 @@ pub mod dev {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl BodyEncoding for crate::HttpResponseBuilder {
|
||||
fn get_encoding(&self) -> Option<ContentEncoding> {
|
||||
self.extensions().get::<Enc>().map(|enc| enc.0)
|
||||
}
|
||||
|
||||
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
||||
self.extensions_mut().insert(Enc(encoding));
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl<B> BodyEncoding for crate::HttpResponse<B> {
|
||||
fn get_encoding(&self) -> Option<ContentEncoding> {
|
||||
self.extensions().get::<Enc>().map(|enc| enc.0)
|
||||
}
|
||||
|
||||
fn encoding(&mut self, encoding: ContentEncoding) -> &mut Self {
|
||||
self.extensions_mut().insert(Enc(encoding));
|
||||
self
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,19 +1,27 @@
|
||||
use std::cell::{Ref, RefCell, RefMut};
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, net};
|
||||
use std::{
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
fmt, net,
|
||||
rc::Rc,
|
||||
str,
|
||||
};
|
||||
|
||||
use actix_http::http::{HeaderMap, Method, Uri, Version};
|
||||
use actix_http::{Error, Extensions, HttpMessage, Message, Payload, RequestHead};
|
||||
use actix_http::{
|
||||
http::{HeaderMap, Method, Uri, Version},
|
||||
Error, Extensions, HttpMessage, Message, Payload, RequestHead,
|
||||
};
|
||||
use actix_router::{Path, Url};
|
||||
use actix_utils::future::{ok, Ready};
|
||||
#[cfg(feature = "cookies")]
|
||||
use cookie::{Cookie, ParseError as CookieParseError};
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::app_service::AppInitServiceState;
|
||||
use crate::config::AppConfig;
|
||||
use crate::error::UrlGenerationError;
|
||||
use crate::extract::FromRequest;
|
||||
use crate::info::ConnectionInfo;
|
||||
use crate::rmap::ResourceMap;
|
||||
use crate::{
|
||||
app_service::AppInitServiceState, config::AppConfig, error::UrlGenerationError,
|
||||
extract::FromRequest, info::ConnectionInfo, rmap::ResourceMap,
|
||||
};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
struct Cookies(Vec<Cookie<'static>>);
|
||||
|
||||
#[derive(Clone)]
|
||||
/// An HTTP Request
|
||||
@ -260,6 +268,42 @@ impl HttpRequest {
|
||||
fn app_state(&self) -> &AppInitServiceState {
|
||||
&*self.inner.app_state
|
||||
}
|
||||
|
||||
/// Load request cookies.
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
|
||||
use actix_http::http::header::COOKIE;
|
||||
|
||||
if self.extensions().get::<Cookies>().is_none() {
|
||||
let mut cookies = Vec::new();
|
||||
for hdr in self.headers().get_all(COOKIE) {
|
||||
let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
|
||||
for cookie_str in s.split(';').map(|s| s.trim()) {
|
||||
if !cookie_str.is_empty() {
|
||||
cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.extensions_mut().insert(Cookies(cookies));
|
||||
}
|
||||
|
||||
Ok(Ref::map(self.extensions(), |ext| {
|
||||
&ext.get::<Cookies>().unwrap().0
|
||||
}))
|
||||
}
|
||||
|
||||
/// Return request cookie.
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
|
||||
if let Ok(cookies) = self.cookies() {
|
||||
for cookie in cookies.iter() {
|
||||
if cookie.name() == name {
|
||||
return Some(cookie.to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl HttpMessage for HttpRequest {
|
||||
|
@ -3,11 +3,10 @@ use std::fmt;
|
||||
use actix_http::{
|
||||
error::InternalError,
|
||||
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
|
||||
ResponseBuilder,
|
||||
};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
|
||||
use crate::{Error, HttpRequest, HttpResponse};
|
||||
use crate::{Error, HttpRequest, HttpResponse, HttpResponseBuilder};
|
||||
|
||||
/// Trait implemented by types that can be converted to an HTTP response.
|
||||
///
|
||||
@ -66,11 +65,32 @@ impl Responder for HttpResponse {
|
||||
}
|
||||
}
|
||||
|
||||
impl Responder for actix_http::Response {
|
||||
#[inline]
|
||||
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
|
||||
HttpResponse::from(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Responder for HttpResponseBuilder {
|
||||
#[inline]
|
||||
fn respond_to(mut self, _: &HttpRequest) -> HttpResponse {
|
||||
self.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Responder for actix_http::ResponseBuilder {
|
||||
#[inline]
|
||||
fn respond_to(mut self, _: &HttpRequest) -> HttpResponse {
|
||||
HttpResponse::from(self.finish())
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Responder> Responder for Option<T> {
|
||||
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
|
||||
match self {
|
||||
Some(t) => t.respond_to(req),
|
||||
None => HttpResponse::build(StatusCode::NOT_FOUND).finish(),
|
||||
Some(val) => val.respond_to(req),
|
||||
None => HttpResponse::new(StatusCode::NOT_FOUND),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -88,13 +108,6 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
impl Responder for ResponseBuilder {
|
||||
#[inline]
|
||||
fn respond_to(mut self, _: &HttpRequest) -> HttpResponse {
|
||||
self.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Responder> Responder for (T, StatusCode) {
|
||||
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
|
||||
let mut res = self.0.respond_to(req);
|
||||
|
968
src/response.rs
Normal file
968
src/response.rs
Normal file
@ -0,0 +1,968 @@
|
||||
use std::{
|
||||
cell::{Ref, RefMut},
|
||||
convert::TryInto,
|
||||
fmt,
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use actix_http::{
|
||||
body::{Body, BodyStream, MessageBody, ResponseBody},
|
||||
http::{
|
||||
header::{self, HeaderMap, HeaderName, IntoHeaderPair, IntoHeaderValue},
|
||||
ConnectionType, Error as HttpError, StatusCode,
|
||||
},
|
||||
Extensions, Response, ResponseHead,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use futures_core::Stream;
|
||||
use serde::Serialize;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use actix_http::http::header::HeaderValue;
|
||||
#[cfg(feature = "cookies")]
|
||||
use cookie::{Cookie, CookieJar};
|
||||
|
||||
use crate::error::Error;
|
||||
|
||||
/// 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, Error>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
if let Some(err) = self.error.take() {
|
||||
eprintln!("httpresponse future error");
|
||||
return Poll::Ready(Ok(Response::from_error(err).into_body()));
|
||||
}
|
||||
|
||||
let res = &mut self.res;
|
||||
actix_rt::pin!(res);
|
||||
|
||||
res.poll(cx)
|
||||
}
|
||||
}
|
||||
|
||||
/// An HTTP response builder.
|
||||
///
|
||||
/// This type can be used to construct an instance of `Response` through a builder-like pattern.
|
||||
pub struct HttpResponseBuilder {
|
||||
head: Option<ResponseHead>,
|
||||
err: Option<HttpError>,
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: Option<CookieJar>,
|
||||
}
|
||||
|
||||
impl HttpResponseBuilder {
|
||||
#[inline]
|
||||
/// Create response builder
|
||||
pub fn new(status: StatusCode) -> Self {
|
||||
Self {
|
||||
head: Some(ResponseHead::new(status)),
|
||||
err: None,
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set HTTP status code of this response.
|
||||
#[inline]
|
||||
pub fn status(&mut self, status: StatusCode) -> &mut Self {
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.status = status;
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_web::{HttpResponse, http::header};
|
||||
///
|
||||
/// HttpResponse::Ok()
|
||||
/// .insert_header(header::ContentType(mime::APPLICATION_JSON))
|
||||
/// .insert_header(("X-TEST", "value"))
|
||||
/// .finish();
|
||||
/// ```
|
||||
pub fn insert_header<H>(&mut self, header: H) -> &mut Self
|
||||
where
|
||||
H: IntoHeaderPair,
|
||||
{
|
||||
if let Some(parts) = self.inner() {
|
||||
match header.try_into_header_pair() {
|
||||
Ok((key, value)) => {
|
||||
parts.headers.insert(key, value);
|
||||
}
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
};
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Append a header, keeping any that were set with an equivalent field name.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_web::{HttpResponse, http::header};
|
||||
///
|
||||
/// HttpResponse::Ok()
|
||||
/// .append_header(header::ContentType(mime::APPLICATION_JSON))
|
||||
/// .append_header(("X-TEST", "value1"))
|
||||
/// .append_header(("X-TEST", "value2"))
|
||||
/// .finish();
|
||||
/// ```
|
||||
pub fn append_header<H>(&mut self, header: H) -> &mut Self
|
||||
where
|
||||
H: IntoHeaderPair,
|
||||
{
|
||||
if let Some(parts) = self.inner() {
|
||||
match header.try_into_header_pair() {
|
||||
Ok((key, value)) => parts.headers.append(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
};
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaced with [`Self::insert_header()`].
|
||||
#[deprecated = "Replaced with `insert_header((key, value))`."]
|
||||
pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self
|
||||
where
|
||||
K: TryInto<HeaderName>,
|
||||
K::Error: Into<HttpError>,
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
if self.err.is_some() {
|
||||
return self;
|
||||
}
|
||||
|
||||
match (key.try_into(), value.try_into_value()) {
|
||||
(Ok(name), Ok(value)) => return self.insert_header((name, value)),
|
||||
(Err(err), _) => self.err = Some(err.into()),
|
||||
(_, Err(err)) => self.err = Some(err.into()),
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Replaced with [`Self::append_header()`].
|
||||
#[deprecated = "Replaced with `append_header((key, value))`."]
|
||||
pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self
|
||||
where
|
||||
K: TryInto<HeaderName>,
|
||||
K::Error: Into<HttpError>,
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
if self.err.is_some() {
|
||||
return self;
|
||||
}
|
||||
|
||||
match (key.try_into(), value.try_into_value()) {
|
||||
(Ok(name), Ok(value)) => return self.append_header((name, value)),
|
||||
(Err(err), _) => self.err = Some(err.into()),
|
||||
(_, Err(err)) => self.err = Some(err.into()),
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Set the custom reason for the response.
|
||||
#[inline]
|
||||
pub fn reason(&mut self, reason: &'static str) -> &mut Self {
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.reason = Some(reason);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set connection type to KeepAlive
|
||||
#[inline]
|
||||
pub fn keep_alive(&mut self) -> &mut Self {
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.set_connection_type(ConnectionType::KeepAlive);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set connection type to Upgrade
|
||||
#[inline]
|
||||
pub fn upgrade<V>(&mut self, value: V) -> &mut Self
|
||||
where
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.set_connection_type(ConnectionType::Upgrade);
|
||||
}
|
||||
|
||||
if let Ok(value) = value.try_into_value() {
|
||||
self.insert_header((header::UPGRADE, value));
|
||||
}
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Force close connection, even if it is marked as keep-alive
|
||||
#[inline]
|
||||
pub fn force_close(&mut self) -> &mut Self {
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.set_connection_type(ConnectionType::Close);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Disable chunked transfer encoding for HTTP/1.1 streaming responses.
|
||||
#[inline]
|
||||
pub fn no_chunking(&mut self, len: u64) -> &mut Self {
|
||||
let mut buf = itoa::Buffer::new();
|
||||
self.insert_header((header::CONTENT_LENGTH, buf.format(len)));
|
||||
|
||||
if let Some(parts) = self.inner() {
|
||||
parts.no_chunking(true);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set response content type.
|
||||
#[inline]
|
||||
pub fn content_type<V>(&mut self, value: V) -> &mut Self
|
||||
where
|
||||
V: IntoHeaderValue,
|
||||
{
|
||||
if let Some(parts) = self.inner() {
|
||||
match value.try_into_value() {
|
||||
Ok(value) => {
|
||||
parts.headers.insert(header::CONTENT_TYPE, value);
|
||||
}
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
};
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Set a cookie.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_web::{HttpResponse, cookie::Cookie};
|
||||
///
|
||||
/// HttpResponse::Ok()
|
||||
/// .cookie(
|
||||
/// Cookie::build("name", "value")
|
||||
/// .domain("www.rust-lang.org")
|
||||
/// .path("/")
|
||||
/// .secure(true)
|
||||
/// .http_only(true)
|
||||
/// .finish(),
|
||||
/// )
|
||||
/// .finish();
|
||||
/// ```
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn cookie<'c>(&mut self, cookie: Cookie<'c>) -> &mut Self {
|
||||
if self.cookies.is_none() {
|
||||
let mut jar = CookieJar::new();
|
||||
jar.add(cookie.into_owned());
|
||||
self.cookies = Some(jar)
|
||||
} else {
|
||||
self.cookies.as_mut().unwrap().add(cookie.into_owned());
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// Remove cookie.
|
||||
///
|
||||
/// A `Set-Cookie` header is added that will delete a cookie with the same name from the client.
|
||||
///
|
||||
/// ```
|
||||
/// use actix_web::{HttpRequest, HttpResponse, Responder};
|
||||
///
|
||||
/// async fn handler(req: HttpRequest) -> impl Responder {
|
||||
/// let mut builder = HttpResponse::Ok();
|
||||
///
|
||||
/// if let Some(ref cookie) = req.cookie("name") {
|
||||
/// builder.del_cookie(cookie);
|
||||
/// }
|
||||
///
|
||||
/// builder.finish()
|
||||
/// }
|
||||
/// ```
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn del_cookie(&mut self, cookie: &Cookie<'_>) -> &mut Self {
|
||||
if self.cookies.is_none() {
|
||||
self.cookies = Some(CookieJar::new())
|
||||
}
|
||||
let jar = self.cookies.as_mut().unwrap();
|
||||
let cookie = cookie.clone().into_owned();
|
||||
jar.add_original(cookie.clone());
|
||||
jar.remove(cookie);
|
||||
self
|
||||
}
|
||||
|
||||
/// Responses extensions
|
||||
#[inline]
|
||||
pub fn extensions(&self) -> Ref<'_, Extensions> {
|
||||
let head = self.head.as_ref().expect("cannot reuse response builder");
|
||||
head.extensions()
|
||||
}
|
||||
|
||||
/// Mutable reference to a the response's extensions
|
||||
#[inline]
|
||||
pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> {
|
||||
let head = self.head.as_ref().expect("cannot reuse response builder");
|
||||
head.extensions_mut()
|
||||
}
|
||||
|
||||
/// Set a body and generate `Response`.
|
||||
///
|
||||
/// `ResponseBuilder` can not be used after this call.
|
||||
#[inline]
|
||||
pub fn body<B: Into<Body>>(&mut self, body: B) -> HttpResponse {
|
||||
self.message_body(body.into())
|
||||
}
|
||||
|
||||
/// Set a body and generate `Response`.
|
||||
///
|
||||
/// `ResponseBuilder` can not be used after this call.
|
||||
pub fn message_body<B>(&mut self, body: B) -> HttpResponse<B> {
|
||||
if let Some(err) = self.err.take() {
|
||||
return HttpResponse::from_error(Error::from(err)).into_body();
|
||||
}
|
||||
|
||||
// allow unused mut when cookies feature is disabled
|
||||
#[allow(unused_mut)]
|
||||
let mut head = self.head.take().expect("cannot reuse response builder");
|
||||
|
||||
let mut res = HttpResponse::with_body(StatusCode::OK, body);
|
||||
*res.head_mut() = head;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
if let Some(ref jar) = self.cookies {
|
||||
for cookie in jar.delta() {
|
||||
match HeaderValue::from_str(&cookie.to_string()) {
|
||||
Ok(val) => res.headers_mut().append(header::SET_COOKIE, val),
|
||||
Err(err) => return HttpResponse::from_error(Error::from(err)).into_body(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
}
|
||||
|
||||
/// Set a streaming body and generate `Response`.
|
||||
///
|
||||
/// `ResponseBuilder` can not be used after this call.
|
||||
#[inline]
|
||||
pub fn streaming<S, E>(&mut self, stream: S) -> HttpResponse
|
||||
where
|
||||
S: Stream<Item = Result<Bytes, E>> + Unpin + 'static,
|
||||
E: Into<Error> + 'static,
|
||||
{
|
||||
self.body(Body::from_message(BodyStream::new(stream)))
|
||||
}
|
||||
|
||||
/// Set a json body and generate `Response`
|
||||
///
|
||||
/// `ResponseBuilder` can not be used after this call.
|
||||
pub fn json(&mut self, value: impl Serialize) -> HttpResponse {
|
||||
match serde_json::to_string(&value) {
|
||||
Ok(body) => {
|
||||
let contains = if let Some(parts) = self.inner() {
|
||||
parts.headers.contains_key(header::CONTENT_TYPE)
|
||||
} else {
|
||||
true
|
||||
};
|
||||
|
||||
if !contains {
|
||||
self.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
|
||||
}
|
||||
|
||||
self.body(Body::from(body))
|
||||
}
|
||||
Err(e) => HttpResponse::from_error(Error::from(e)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set an empty body and generate `Response`
|
||||
///
|
||||
/// `ResponseBuilder` can not be used after this call.
|
||||
#[inline]
|
||||
pub fn finish(&mut self) -> HttpResponse {
|
||||
self.body(Body::Empty)
|
||||
}
|
||||
|
||||
/// This method construct new `ResponseBuilder`
|
||||
pub fn take(&mut self) -> Self {
|
||||
Self {
|
||||
head: self.head.take(),
|
||||
err: self.err.take(),
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: self.cookies.take(),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inner(&mut self) -> Option<&mut ResponseHead> {
|
||||
if self.err.is_some() {
|
||||
return None;
|
||||
}
|
||||
|
||||
self.head.as_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HttpResponseBuilder> for HttpResponse {
|
||||
fn from(mut builder: HttpResponseBuilder) -> Self {
|
||||
builder.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<HttpResponseBuilder> for Response {
|
||||
fn from(mut builder: HttpResponseBuilder) -> Self {
|
||||
builder.finish().into()
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for HttpResponseBuilder {
|
||||
type Output = Result<HttpResponse, Error>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
eprintln!("httpresponse future error");
|
||||
Poll::Ready(Ok(self.finish()))
|
||||
}
|
||||
}
|
||||
|
||||
#[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 serde_json::json;
|
||||
|
||||
use super::{HttpResponse as Response, HttpResponseBuilder as ResponseBuilder};
|
||||
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 = Response::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("Response"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_basic_builder() {
|
||||
let resp = Response::Ok().insert_header(("X-TEST", "value")).finish();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_upgrade() {
|
||||
let resp = ResponseBuilder::new(StatusCode::OK)
|
||||
.upgrade("websocket")
|
||||
.finish();
|
||||
assert!(resp.upgrade());
|
||||
assert_eq!(
|
||||
resp.headers().get(header::UPGRADE).unwrap(),
|
||||
HeaderValue::from_static("websocket")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_force_close() {
|
||||
let resp = ResponseBuilder::new(StatusCode::OK).force_close().finish();
|
||||
assert!(!resp.keep_alive())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_content_type() {
|
||||
let resp = ResponseBuilder::new(StatusCode::OK)
|
||||
.content_type("text/plain")
|
||||
.body(Body::Empty);
|
||||
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 = Response::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(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
|
||||
let mut resp = Response::Ok().json(&["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(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
|
||||
// content type override
|
||||
let mut resp = Response::Ok()
|
||||
.insert_header((CONTENT_TYPE, "text/json"))
|
||||
.json(&vec!["v1", "v2", "v3"]);
|
||||
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(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_serde_json_in_body() {
|
||||
use serde_json::json;
|
||||
let mut resp = Response::Ok().body(json!({"test-key":"test-value"}));
|
||||
assert_eq!(
|
||||
read_body(resp.take_body()).await.as_ref(),
|
||||
br#"{"test-key":"test-value"}"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_builder_header_insert_kv() {
|
||||
let mut res = Response::Ok();
|
||||
res.insert_header(("Content-Type", "application/octet-stream"));
|
||||
let res = res.finish();
|
||||
|
||||
assert_eq!(
|
||||
res.headers().get("Content-Type"),
|
||||
Some(&HeaderValue::from_static("application/octet-stream"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_builder_header_insert_typed() {
|
||||
let mut res = Response::Ok();
|
||||
res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
|
||||
let res = res.finish();
|
||||
|
||||
assert_eq!(
|
||||
res.headers().get("Content-Type"),
|
||||
Some(&HeaderValue::from_static("application/octet-stream"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_builder_header_append_kv() {
|
||||
let mut res = Response::Ok();
|
||||
res.append_header(("Content-Type", "application/octet-stream"));
|
||||
res.append_header(("Content-Type", "application/json"));
|
||||
let res = res.finish();
|
||||
|
||||
let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
|
||||
assert_eq!(headers.len(), 2);
|
||||
assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
|
||||
assert!(headers.contains(&HeaderValue::from_static("application/json")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_builder_header_append_typed() {
|
||||
let mut res = Response::Ok();
|
||||
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM));
|
||||
res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON));
|
||||
let res = res.finish();
|
||||
|
||||
let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect();
|
||||
assert_eq!(headers.len(), 2);
|
||||
assert!(headers.contains(&HeaderValue::from_static("application/octet-stream")));
|
||||
assert!(headers.contains(&HeaderValue::from_static("application/json")));
|
||||
}
|
||||
}
|
@ -10,12 +10,15 @@ use actix_http::{
|
||||
use actix_router::{IntoPattern, Path, Resource, ResourceDef, Url};
|
||||
use actix_service::{IntoServiceFactory, ServiceFactory};
|
||||
|
||||
use crate::config::{AppConfig, AppService};
|
||||
use crate::dev::insert_slash;
|
||||
use crate::guard::Guard;
|
||||
use crate::info::ConnectionInfo;
|
||||
use crate::request::HttpRequest;
|
||||
use crate::rmap::ResourceMap;
|
||||
use crate::{
|
||||
config::{AppConfig, AppService},
|
||||
HttpResponse,
|
||||
};
|
||||
|
||||
pub trait HttpServiceFactory {
|
||||
fn register(self, config: &mut AppService);
|
||||
@ -99,13 +102,14 @@ impl ServiceRequest {
|
||||
/// Create service response
|
||||
#[inline]
|
||||
pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> {
|
||||
ServiceResponse::new(self.req, res.into())
|
||||
let res = HttpResponse::from(res.into());
|
||||
ServiceResponse::new(self.req, res)
|
||||
}
|
||||
|
||||
/// Create service response for error
|
||||
#[inline]
|
||||
pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> {
|
||||
let res: Response = err.into().into();
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
ServiceResponse::new(self.req, res.into_body())
|
||||
}
|
||||
|
||||
@ -315,23 +319,19 @@ impl fmt::Debug for ServiceRequest {
|
||||
|
||||
pub struct ServiceResponse<B = Body> {
|
||||
request: HttpRequest,
|
||||
response: Response<B>,
|
||||
response: HttpResponse<B>,
|
||||
}
|
||||
|
||||
impl<B> ServiceResponse<B> {
|
||||
/// Create service response instance
|
||||
pub fn new(request: HttpRequest, response: Response<B>) -> Self {
|
||||
pub fn new(request: HttpRequest, response: HttpResponse<B>) -> Self {
|
||||
ServiceResponse { request, response }
|
||||
}
|
||||
|
||||
/// Create service response from the error
|
||||
pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
|
||||
let e: Error = err.into();
|
||||
let res: Response = e.into();
|
||||
ServiceResponse {
|
||||
request,
|
||||
response: res.into_body(),
|
||||
}
|
||||
let response = HttpResponse::from_error(err.into()).into_body();
|
||||
ServiceResponse { request, response }
|
||||
}
|
||||
|
||||
/// Create service response for error
|
||||
@ -342,7 +342,7 @@ impl<B> ServiceResponse<B> {
|
||||
|
||||
/// Create service response
|
||||
#[inline]
|
||||
pub fn into_response<B1>(self, response: Response<B1>) -> ServiceResponse<B1> {
|
||||
pub fn into_response<B1>(self, response: HttpResponse<B1>) -> ServiceResponse<B1> {
|
||||
ServiceResponse::new(self.request, response)
|
||||
}
|
||||
|
||||
@ -354,13 +354,13 @@ impl<B> ServiceResponse<B> {
|
||||
|
||||
/// Get reference to response
|
||||
#[inline]
|
||||
pub fn response(&self) -> &Response<B> {
|
||||
pub fn response(&self) -> &HttpResponse<B> {
|
||||
&self.response
|
||||
}
|
||||
|
||||
/// Get mutable reference to response
|
||||
#[inline]
|
||||
pub fn response_mut(&mut self) -> &mut Response<B> {
|
||||
pub fn response_mut(&mut self) -> &mut HttpResponse<B> {
|
||||
&mut self.response
|
||||
}
|
||||
|
||||
@ -376,8 +376,8 @@ impl<B> ServiceResponse<B> {
|
||||
self.response.headers()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
/// Returns mutable response's headers.
|
||||
#[inline]
|
||||
pub fn headers_mut(&mut self) -> &mut HeaderMap {
|
||||
self.response.headers_mut()
|
||||
}
|
||||
@ -391,7 +391,7 @@ impl<B> ServiceResponse<B> {
|
||||
match f(&mut self) {
|
||||
Ok(_) => self,
|
||||
Err(err) => {
|
||||
let res: Response = err.into().into();
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
ServiceResponse::new(self.request, res.into_body())
|
||||
}
|
||||
}
|
||||
@ -418,9 +418,15 @@ impl<B> ServiceResponse<B> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<B> From<ServiceResponse<B>> for HttpResponse<B> {
|
||||
fn from(res: ServiceResponse<B>) -> HttpResponse<B> {
|
||||
res.response
|
||||
}
|
||||
}
|
||||
|
||||
impl<B> From<ServiceResponse<B>> for Response<B> {
|
||||
fn from(res: ServiceResponse<B>) -> Response<B> {
|
||||
res.response
|
||||
res.response.into()
|
||||
}
|
||||
}
|
||||
|
||||
|
48
src/test.rs
48
src/test.rs
@ -2,8 +2,6 @@
|
||||
|
||||
use std::{net::SocketAddr, rc::Rc};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use actix_http::cookie::Cookie;
|
||||
pub use actix_http::test::TestBuffer;
|
||||
use actix_http::{
|
||||
http::{header::IntoHeaderPair, Method, StatusCode, Uri, Version},
|
||||
@ -17,6 +15,8 @@ use futures_core::Stream;
|
||||
use futures_util::StreamExt as _;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use crate::cookie::{Cookie, CookieJar};
|
||||
use crate::{
|
||||
app_service::AppInitServiceState,
|
||||
config::AppConfig,
|
||||
@ -26,7 +26,7 @@ use crate::{
|
||||
rmap::ResourceMap,
|
||||
service::{ServiceRequest, ServiceResponse},
|
||||
web::{Bytes, BytesMut},
|
||||
Error, HttpRequest, HttpResponse,
|
||||
Error, HttpRequest, HttpResponse, HttpResponseBuilder,
|
||||
};
|
||||
|
||||
/// Create service that always responds with `HttpResponse::Ok()` and no body.
|
||||
@ -40,7 +40,7 @@ pub fn default_service(
|
||||
status_code: StatusCode,
|
||||
) -> impl Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error> {
|
||||
(move |req: ServiceRequest| {
|
||||
ok(req.into_response(HttpResponse::build(status_code).finish()))
|
||||
ok(req.into_response(HttpResponseBuilder::new(status_code).finish()))
|
||||
})
|
||||
.into_service()
|
||||
}
|
||||
@ -359,6 +359,8 @@ pub struct TestRequest {
|
||||
path: Path<Url>,
|
||||
peer_addr: Option<SocketAddr>,
|
||||
app_data: Extensions,
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: CookieJar,
|
||||
}
|
||||
|
||||
impl Default for TestRequest {
|
||||
@ -370,6 +372,8 @@ impl Default for TestRequest {
|
||||
path: Path::new(Url::new(Uri::default())),
|
||||
peer_addr: None,
|
||||
app_data: Extensions::new(),
|
||||
#[cfg(feature = "cookies")]
|
||||
cookies: CookieJar::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -445,7 +449,7 @@ impl TestRequest {
|
||||
/// Set cookie for this request.
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||
self.req.cookie(cookie);
|
||||
self.cookies.add(cookie.into_owned());
|
||||
self
|
||||
}
|
||||
|
||||
@ -507,16 +511,42 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
fn finish(&mut self) -> Request {
|
||||
// mut used when cookie feature is enabled
|
||||
#[allow(unused_mut)]
|
||||
let mut req = self.req.finish();
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
{
|
||||
use actix_http::http::header::{HeaderValue, COOKIE};
|
||||
|
||||
let cookie: String = self
|
||||
.cookies
|
||||
.delta()
|
||||
// ensure only name=value is written to cookie header
|
||||
.map(|c| c.stripped().encoded().to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("; ");
|
||||
|
||||
if !cookie.is_empty() {
|
||||
req.headers_mut()
|
||||
.insert(COOKIE, HeaderValue::from_str(&cookie).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
req
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `Request` instance
|
||||
pub fn to_request(mut self) -> Request {
|
||||
let mut req = self.req.finish();
|
||||
let mut req = self.finish();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
req
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `ServiceRequest` instance
|
||||
pub fn to_srv_request(mut self) -> ServiceRequest {
|
||||
let (mut head, payload) = self.req.finish().into_parts();
|
||||
let (mut head, payload) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
@ -535,7 +565,7 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` instance
|
||||
pub fn to_http_request(mut self) -> HttpRequest {
|
||||
let (mut head, _) = self.req.finish().into_parts();
|
||||
let (mut head, _) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
@ -546,7 +576,7 @@ impl TestRequest {
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
||||
let (mut head, payload) = self.req.finish().into_parts();
|
||||
let (mut head, payload) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
self.path.get_mut().update(&head.uri);
|
||||
|
||||
|
@ -225,7 +225,7 @@ where
|
||||
/// .content_type(|mime| mime == mime::TEXT_PLAIN)
|
||||
/// // use custom error handler
|
||||
/// .error_handler(|err, req| {
|
||||
/// error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into()
|
||||
/// error::InternalError::from_response(err, HttpResponse::Conflict().into()).into()
|
||||
/// });
|
||||
///
|
||||
/// App::new()
|
||||
@ -486,7 +486,7 @@ mod tests {
|
||||
};
|
||||
let resp =
|
||||
HttpResponse::BadRequest().body(serde_json::to_string(&msg).unwrap());
|
||||
InternalError::from_response(err, resp).into()
|
||||
InternalError::from_response(err, resp.into()).into()
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
||||
|
@ -149,7 +149,7 @@ where
|
||||
/// .app_data(PathConfig::default().error_handler(|err, req| {
|
||||
/// error::InternalError::from_response(
|
||||
/// err,
|
||||
/// HttpResponse::Conflict().finish(),
|
||||
/// HttpResponse::Conflict().into(),
|
||||
/// )
|
||||
/// .into()
|
||||
/// }))
|
||||
@ -292,15 +292,18 @@ mod tests {
|
||||
async fn test_custom_err_handler() {
|
||||
let (req, mut pl) = TestRequest::with_uri("/name/user1/")
|
||||
.app_data(PathConfig::default().error_handler(|err, _| {
|
||||
error::InternalError::from_response(err, HttpResponse::Conflict().finish())
|
||||
.into()
|
||||
error::InternalError::from_response(
|
||||
err,
|
||||
HttpResponse::Conflict().finish().into(),
|
||||
)
|
||||
.into()
|
||||
}))
|
||||
.to_http_parts();
|
||||
|
||||
let s = Path::<(usize,)>::from_request(&req, &mut pl)
|
||||
.await
|
||||
.unwrap_err();
|
||||
let res: HttpResponse = s.into();
|
||||
let res = HttpResponse::from_error(s.into());
|
||||
|
||||
assert_eq!(res.status(), http::StatusCode::CONFLICT);
|
||||
}
|
||||
|
@ -166,7 +166,7 @@ where
|
||||
/// let query_cfg = web::QueryConfig::default()
|
||||
/// // use custom error handler
|
||||
/// .error_handler(|err, req| {
|
||||
/// error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into()
|
||||
/// error::InternalError::from_response(err, HttpResponse::Conflict().into()).into()
|
||||
/// });
|
||||
///
|
||||
/// App::new()
|
||||
@ -267,7 +267,7 @@ mod tests {
|
||||
let req = TestRequest::with_uri("/name/user1/")
|
||||
.app_data(QueryConfig::default().error_handler(|e, _| {
|
||||
let resp = HttpResponse::UnprocessableEntity().finish();
|
||||
InternalError::from_response(e, resp).into()
|
||||
InternalError::from_response(e, resp.into()).into()
|
||||
}))
|
||||
.to_srv_request();
|
||||
|
||||
|
Reference in New Issue
Block a user