Add 'Response::cookies()' method for easy cookie retrieval.

This commit is contained in:
Sergio Benitez 2018-04-14 16:24:41 -07:00
parent efc511c6dc
commit a96ba1c296
2 changed files with 31 additions and 1 deletions

View File

@ -358,6 +358,12 @@ impl<'a> fmt::Debug for Cookies<'a> {
}
}
impl<'c> From<Cookie<'c>> for Header<'static> {
fn from(cookie: Cookie) -> Header<'static> {
Header::new("Set-Cookie", cookie.encoded().to_string())
}
}
impl<'a, 'c> From<&'a Cookie<'c>> for Header<'static> {
fn from(cookie: &Cookie) -> Header<'static> {
Header::new("Set-Cookie", cookie.encoded().to_string())

View File

@ -2,7 +2,7 @@ use std::{io, fmt, str};
use std::borrow::Cow;
use response::Responder;
use http::{Header, HeaderMap, Status, ContentType};
use http::{Header, HeaderMap, Status, ContentType, Cookie};
/// The default size, in bytes, of a chunk for streamed responses.
pub const DEFAULT_CHUNK_SIZE: u64 = 4096;
@ -696,6 +696,30 @@ impl<'r> Response<'r> {
self.status = Some(Status::new(code, reason));
}
/// Returns a vector of the cookies set in `self` as identified by the
/// `Set-Cookie` header. Malformed cookies are skipped.
///
/// # Example
///
/// ```rust
/// use rocket::Response;
/// use rocket::http::Cookie;
///
/// let mut response = Response::new();
/// response.set_header(Cookie::new("hello", "world!"));
/// assert_eq!(response.cookies(), vec![Cookie::new("hello", "world!")]);
/// ```
pub fn cookies(&self) -> Vec<Cookie> {
let mut cookies = vec![];
for header in self.headers().get("Set-Cookie") {
if let Ok(cookie) = Cookie::parse_encoded(header) {
cookies.push(cookie);
}
}
cookies
}
/// Returns a [`HeaderMap`](/rocket/http/struct.HeaderMap.html) of all of
/// the headers in `self`.
///