Merge pull request #166 from s-panferov/feature/client-cookies
Add more functions for client to work with cookies.
This commit is contained in:
@@ -66,11 +66,17 @@ impl Cookies {
|
||||
/// to manipulate cookies and create a corresponding `SetCookie` header afterwards.
|
||||
pub fn to_cookie_jar(&self, key: &[u8]) -> CookieJar<'static> {
|
||||
let mut jar = CookieJar::new(key);
|
||||
for cookie in self.0.iter() {
|
||||
jar.add_original((*cookie).clone());
|
||||
for cookie in self.iter() {
|
||||
jar.add_original(cookie.clone());
|
||||
}
|
||||
jar
|
||||
}
|
||||
|
||||
/// Extracts all cookies from `CookieJar` and creates Cookie header.
|
||||
/// Useful for clients.
|
||||
pub fn from_cookie_jar(jar: &CookieJar) -> Cookies {
|
||||
Cookies(jar.iter().collect())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,4 +102,15 @@ fn test_fmt() {
|
||||
assert_eq!(headers.to_string()[], "Cookie: foo=bar; baz=quux\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_jar() {
|
||||
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
|
||||
let cookies = Cookies(vec![cookie]);
|
||||
let jar = cookies.to_cookie_jar(&[]);
|
||||
let new_cookies = Cookies::from_cookie_jar(&jar);
|
||||
|
||||
assert_eq!(cookies, new_cookies);
|
||||
}
|
||||
|
||||
|
||||
bench_header!(bench, Cookies, { vec![b"foo=bar; baz=quux".to_vec()] })
|
||||
|
||||
@@ -63,6 +63,14 @@ impl SetCookie {
|
||||
pub fn from_cookie_jar(jar: &CookieJar) -> SetCookie {
|
||||
SetCookie(jar.delta())
|
||||
}
|
||||
|
||||
/// Use this on client to apply changes from SetCookie to CookieJar.
|
||||
/// Note that this will `panic!` if `CookieJar` is not root.
|
||||
pub fn apply_to_cookie_jar(&self, jar: &mut CookieJar) {
|
||||
for cookie in self.iter() {
|
||||
jar.add_original(cookie.clone())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -88,3 +96,18 @@ fn test_fmt() {
|
||||
|
||||
assert_eq!(headers.to_string()[], "Set-Cookie: foo=bar; HttpOnly; Path=/p\r\nSet-Cookie: baz=quux; Path=/\r\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_jar() {
|
||||
let jar = CookieJar::new("secret".as_bytes());
|
||||
let cookie = Cookie::new("foo".to_string(), "bar".to_string());
|
||||
jar.encrypted().add(cookie);
|
||||
|
||||
let cookies = SetCookie::from_cookie_jar(&jar);
|
||||
|
||||
let mut new_jar = CookieJar::new("secret".as_bytes());
|
||||
cookies.apply_to_cookie_jar(&mut new_jar);
|
||||
|
||||
assert_eq!(jar.encrypted().find("foo"), new_jar.encrypted().find("foo"));
|
||||
assert_eq!(jar.iter().collect::<Vec<Cookie>>(), new_jar.iter().collect::<Vec<Cookie>>());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user