From 72e684f235b18aa6201dfda0725537f3b6a415d5 Mon Sep 17 00:00:00 2001 From: Sebastian Detert Date: Mon, 4 Dec 2023 22:56:48 +0100 Subject: [PATCH] feat: add .customize().add_cookie() --- actix-web/src/response/customize_responder.rs | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/actix-web/src/response/customize_responder.rs b/actix-web/src/response/customize_responder.rs index aad0039e0..bf3f8cffb 100644 --- a/actix-web/src/response/customize_responder.rs +++ b/actix-web/src/response/customize_responder.rs @@ -5,6 +5,12 @@ 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`]. @@ -137,6 +143,21 @@ impl CustomizeResponder { 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 { + 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::::into)? + } + + Ok(self) + } } impl Responder for CustomizeResponder @@ -175,6 +196,7 @@ mod tests { use super::*; use crate::{ + cookie::Cookie, http::{ header::{HeaderValue, CONTENT_TYPE}, StatusCode, @@ -212,6 +234,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_eq!(res.status(), StatusCode::OK); + assert_eq!( + res.cookies().collect::>>(), + vec![Cookie::new("name", "value")] + ); + assert_eq!( + to_bytes(res.into_body()).await.unwrap(), + Bytes::from_static(b"test"), + ); } #[actix_rt::test]