Skip to content

Commit

Permalink
feat: add .customize().add_cookie() (#3215)
Browse files Browse the repository at this point in the history
* feat: add .customize().add_cookie()

* docs: added cookie hint

* fix: added unwrap to test of add_cookie()

* docs: added changelog entry for .customize().add_cookie()

* chore: make append_header infallible

* docs: update changelog

---------

Co-authored-by: Rob Ede <robjtede@icloud.com>
  • Loading branch information
Thomblin and robjtede authored Jun 7, 2024
1 parent cff958e commit 534cfe1
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
1 change: 1 addition & 0 deletions actix-web/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

### Added

- Add `CustomizeResponder::add_cookie()` method.
- Add `guard::GuardContext::app_data()` method.
- Implement `From<Box<dyn ResponseError>>` for `Error`.

Expand Down
42 changes: 41 additions & 1 deletion actix-web/src/response/customize_responder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use actix_http::{

use crate::{HttpRequest, HttpResponse, Responder};

/// Allows overriding status code and headers for a [`Responder`].
/// Allows overriding status code and headers (including 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 +137,29 @@ impl<R: Responder> CustomizeResponder<R> {
Some(&mut self.inner)
}
}

/// Appends a `cookie` to the final response.
///
/// # Errors
///
/// Final response will be an error if `cookie` cannot be converted into a valid header value.
#[cfg(feature = "cookies")]
pub fn add_cookie(mut self, cookie: &crate::cookie::Cookie<'_>) -> Self {
use actix_http::header::{TryIntoHeaderValue as _, SET_COOKIE};

if let Some(inner) = self.inner() {
match cookie.to_string().try_into_value() {
Ok(val) => {
inner.append_headers.append(SET_COOKIE, val);
}
Err(err) => {
self.error = Some(err.into());
}
}
}

self
}
}

impl<T> Responder for CustomizeResponder<T>
Expand Down Expand Up @@ -175,6 +198,7 @@ mod tests {

use super::*;
use crate::{
cookie::Cookie,
http::header::{HeaderValue, CONTENT_TYPE},
test::TestRequest,
};
Expand Down Expand Up @@ -209,6 +233,22 @@ 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"))
.respond_to(&req);

assert!(res.status().is_success());
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

0 comments on commit 534cfe1

Please sign in to comment.