tower_cookies/service/
mod.rs

1//! Middleware to use [`Cookies`].
2
3use self::future::ResponseFuture;
4use crate::Cookies;
5use http::{header, Request, Response};
6use std::task::{Context, Poll};
7use tower_layer::Layer;
8use tower_service::Service;
9
10pub mod future;
11
12/// Middleware to use [`Cookies`].
13#[derive(Clone, Debug)]
14pub struct CookieManager<S> {
15    inner: S,
16}
17
18impl<S> CookieManager<S> {
19    /// Create a new cookie manager.
20    pub fn new(inner: S) -> Self {
21        Self { inner }
22    }
23}
24
25impl<ReqBody, ResBody, S> Service<Request<ReqBody>> for CookieManager<S>
26where
27    S: Service<Request<ReqBody>, Response = Response<ResBody>>,
28{
29    type Response = S::Response;
30    type Error = S::Error;
31    type Future = ResponseFuture<S::Future>;
32
33    #[inline]
34    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
35        self.inner.poll_ready(cx)
36    }
37
38    fn call(&mut self, mut req: Request<ReqBody>) -> Self::Future {
39        let value = req
40            .headers()
41            .get_all(header::COOKIE)
42            .iter()
43            .cloned()
44            .collect();
45        let cookies = Cookies::new(value);
46        req.extensions_mut().insert(cookies.clone());
47
48        ResponseFuture {
49            future: self.inner.call(req),
50            cookies,
51        }
52    }
53}
54
55/// Layer to apply [`CookieManager`] middleware.
56#[derive(Clone, Debug, Default)]
57pub struct CookieManagerLayer {
58    _priv: (),
59}
60
61impl CookieManagerLayer {
62    /// Create a new cookie manager layer.
63    pub fn new() -> Self {
64        Self { _priv: () }
65    }
66}
67
68impl<S> Layer<S> for CookieManagerLayer {
69    type Service = CookieManager<S>;
70
71    fn layer(&self, inner: S) -> Self::Service {
72        CookieManager { inner }
73    }
74}