Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add .customize().add_cookie() #3215

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions actix-web/CHANGES.md
Expand Up @@ -6,6 +6,7 @@

- Updated `zstd` dependency to `0.13`.
- Compression middleware now prefers brotli over zstd over gzip.
- Added .customize().add_cookie() for `CustomizeResponder`

### Fixed

Expand Down
41 changes: 40 additions & 1 deletion actix-web/src/response/customize_responder.rs
Expand Up @@ -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> {
Expand Down Expand Up @@ -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>
Expand Down Expand Up @@ -175,6 +196,7 @@ mod tests {

use super::*;
use crate::{
cookie::Cookie,
http::{
header::{HeaderValue, CONTENT_TYPE},
StatusCode,
Expand Down Expand Up @@ -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]
Expand Down