gotham/middleware/
cookie.rs1use std::pin::Pin;
3
4use cookie::{Cookie, CookieJar};
5use hyper::header::{HeaderMap, HeaderValue, COOKIE};
6
7use super::{Middleware, NewMiddleware};
8use crate::handler::HandlerFuture;
9use crate::state::{FromState, State};
10
11#[derive(Copy, Clone)]
17pub struct CookieParser;
18
19impl CookieParser {
21 pub fn from_state(state: &State) -> CookieJar {
23 HeaderMap::borrow_from(state)
24 .get_all(COOKIE)
25 .iter()
26 .flat_map(HeaderValue::to_str)
27 .flat_map(|cs| cs.split("; "))
28 .flat_map(|cs| Cookie::parse(cs.to_owned()))
29 .fold(CookieJar::new(), |mut jar, cookie| {
30 jar.add_original(cookie);
31 jar
32 })
33 }
34}
35
36impl Middleware for CookieParser {
38 fn call<Chain>(self, mut state: State, chain: Chain) -> Pin<Box<HandlerFuture>>
40 where
41 Chain: FnOnce(State) -> Pin<Box<HandlerFuture>>,
42 {
43 let cookies = { CookieParser::from_state(&state) };
44 state.put(cookies);
45 chain(state)
46 }
47}
48
49impl NewMiddleware for CookieParser {
51 type Instance = Self;
52
53 fn new_middleware(&self) -> anyhow::Result<Self::Instance> {
55 Ok(*self)
56 }
57}