Skip to main content

cookie_monster/
http.rs

1use http::HeaderMap;
2
3use crate::{Cookie, CookieJar};
4
5impl CookieJar {
6    /// Builds a `CookieJar` from the `Cookie` request headers, percent-decoding
7    /// names and values and ignoring cookies that fail to parse.
8    ///
9    /// Duplicate cookie names resolve to the **last** occurrence; see
10    /// [`from_cookie`](CookieJar::from_cookie) for the cookie-shadowing note.
11    pub fn from_headers(headers: &HeaderMap) -> Self {
12        let iter = headers
13            .get_all("cookie")
14            .into_iter()
15            .filter_map(|header| header.to_str().ok())
16            .flat_map(|cookie_str| cookie_str.split(';'))
17            .filter_map(|string| Cookie::parse_cookie_encoded(string).ok());
18
19        CookieJar::from_original(iter)
20    }
21
22    pub fn write_cookies(self, headers: &mut HeaderMap) {
23        for cookie in self.iter_non_original() {
24            if let Some(header) = cookie
25                .serialize_encoded()
26                .ok()
27                .and_then(|string| string.parse().ok())
28            {
29                headers.append("set-cookie", header);
30            }
31        }
32    }
33}