Skip to content

Commit

Permalink
[#201] Response::add_cookie 함수 구현
Browse files Browse the repository at this point in the history
  • Loading branch information
myyrakle committed Dec 24, 2024
1 parent cf54751 commit 5b658e6
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
48 changes: 46 additions & 2 deletions rupring/src/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,6 @@ pub struct Response {
pub body: Vec<u8>,
pub headers: HashMap<HeaderName, Vec<String>>,
pub(crate) next: Option<Box<(Request, Response)>>,
pub(crate) set_cookies: Vec<Cookie>,
}

impl UnwindSafe for Response {}
Expand All @@ -151,7 +150,6 @@ impl Response {
body: Vec::new(),
headers: Default::default(),
next: None,
set_cookies: Vec::new(),
}
}

Expand Down Expand Up @@ -252,6 +250,52 @@ impl Response {

self.header(header::LOCATION, url)
}

/// add a cookie to the response.
/// ```
/// use rupring::HeaderName;
/// use rupring::response::Cookie;
/// let response = rupring::Response::new().add_cookie(Cookie::new("foo", "bar"));
/// assert_eq!(response.headers.get(&HeaderName::from_static("set-cookie")).unwrap(), &vec!["foo=bar".to_string()]);
/// ```
pub fn add_cookie(mut self, cookie: Cookie) -> Self {
let mut cookie_str = format!("{}={}", cookie.name, cookie.value);

if let Some(expires) = cookie.expires {
cookie_str.push_str(&format!("; Expires={}", expires));
}

if let Some(max_age) = cookie.max_age {
cookie_str.push_str(&format!("; Max-Age={}", max_age));
}

if let Some(domain) = cookie.domain {
cookie_str.push_str(&format!("; Domain={}", domain));
}

if let Some(path) = cookie.path {
cookie_str.push_str(&format!("; Path={}", path));
}

if let Some(secure) = cookie.secure {
cookie_str.push_str(&format!("; Secure={}", secure));
}

if let Some(http_only) = cookie.http_only {
cookie_str.push_str(&format!("; HttpOnly={}", http_only));
}

if let Some(same_site) = cookie.same_site {
cookie_str.push_str(&format!("; SameSite={}", same_site));
}

self.headers
.entry(HeaderName::from_static(header::SET_COOKIE))
.or_insert_with(Vec::new)
.push(cookie_str);

return self;
}
}

pub trait IntoResponse {
Expand Down
6 changes: 4 additions & 2 deletions rupring_example/src/domains/root/controller.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use rupring::response::Cookie;

#[derive(Debug, Clone)]
#[rupring::Controller(prefix=/, routes=[index, slow], tags=["root"])]
pub struct RootController {}
Expand All @@ -12,8 +14,8 @@ pub fn index(request: rupring::Request) -> rupring::Response {

rupring::Response::new()
.text("123214")
.header(rupring::header::SET_COOKIE, "foo=bar")
.header(rupring::header::SET_COOKIE, "baz=qux")
.add_cookie(Cookie::new("name", "value").http_only(true).secure(true))
.add_cookie(Cookie::new("name2", "value2").http_only(true).secure(true))
}

#[rupring::Get(path = /slow)]
Expand Down

0 comments on commit 5b658e6

Please sign in to comment.