mirror of
https://github.com/actix/actix-web.git
synced 2024-06-02 21:39:26 +00:00
Merge 173478556c
into 1e2ef6f92f
This commit is contained in:
commit
c1ed3aee56
|
@ -25,6 +25,7 @@
|
|||
|
||||
- Updated `zstd` dependency to `0.13`.
|
||||
- Compression middleware now prefers brotli over zstd over gzip.
|
||||
- Added .customize().add_cookie() for `CustomizeResponder`
|
||||
|
||||
### Fixed
|
||||
|
||||
|
|
|
@ -5,9 +5,15 @@ use actix_http::{
|
|||
StatusCode,
|
||||
};
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
use {
|
||||
actix_http::header::{self, HeaderValue},
|
||||
cookie::Cookie,
|
||||
};
|
||||
|
||||
use crate::{HttpRequest, HttpResponse, Responder};
|
||||
|
||||
/// Allows overriding status code and headers for a [`Responder`].
|
||||
/// Allows overriding status code and headers (cookies) for a [`Responder`].
|
||||
///
|
||||
/// Created by calling the [`customize`](Responder::customize) method on a [`Responder`] type.
|
||||
pub struct CustomizeResponder<R> {
|
||||
|
@ -137,6 +143,21 @@ impl<R: Responder> CustomizeResponder<R> {
|
|||
Some(&mut self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Append a cookie to the final response.
|
||||
///
|
||||
/// # Errors
|
||||
/// Returns an error if the cookie results in a malformed `Set-Cookie` header.
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn add_cookie(mut self, cookie: &Cookie<'_>) -> Result<Self, HttpError> {
|
||||
if let Some(inner) = self.inner() {
|
||||
HeaderValue::from_str(&cookie.to_string())
|
||||
.map(|cookie| inner.append_headers.append(header::SET_COOKIE, cookie))
|
||||
.map_err(Into::<HttpError>::into)?
|
||||
}
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Responder for CustomizeResponder<T>
|
||||
|
@ -175,6 +196,7 @@ mod tests {
|
|||
|
||||
use super::*;
|
||||
use crate::{
|
||||
cookie::Cookie,
|
||||
http::{
|
||||
header::{HeaderValue, CONTENT_TYPE},
|
||||
StatusCode,
|
||||
|
@ -212,6 +234,23 @@ mod tests {
|
|||
to_bytes(res.into_body()).await.unwrap(),
|
||||
Bytes::from_static(b"test"),
|
||||
);
|
||||
|
||||
let res = "test"
|
||||
.to_string()
|
||||
.customize()
|
||||
.add_cookie(&Cookie::new("name", "value"))
|
||||
.unwrap()
|
||||
.respond_to(&req);
|
||||
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert_eq!(
|
||||
res.cookies().collect::<Vec<Cookie<'_>>>(),
|
||||
vec![Cookie::new("name", "value")]
|
||||
);
|
||||
assert_eq!(
|
||||
to_bytes(res.into_body()).await.unwrap(),
|
||||
Bytes::from_static(b"test"),
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
|
|
Loading…
Reference in a new issue