Skip to content
1        10        20        30        40        50        60        70        80        901use actix_web::Error;2use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};3use actix_web::http::header::{CACHE_CONTROL, HeaderValue};4use std::future::{Future, Ready, ready};5use std::pin::Pin;67#[derive(Clone, Debug, Default)]8pub struct CacheControl {9    header_value: Option<HeaderValue>,10}1112impl CacheControl {13    pub fn new(header_value: Option<HeaderValue>) -> Self {14        Self { header_value }15    }16}1718impl<S, B> Transform<S, ServiceRequest> for CacheControl19where20    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,21    S::Future: 'static,22    B: 'static,23{24    type Response = ServiceResponse<B>;25    type Error = Error;26    type InitError = ();27    type Transform = CacheControlMiddleware<S>;28    type Future = Ready<Result<Self::Transform, Self::InitError>>;2930    fn new_transform(&self, service: S) -> Self::Future {31        ready(Ok(CacheControlMiddleware {32            service,33            header_value: self.header_value.clone(),34        }))35    }36}3738pub struct CacheControlMiddleware<S> {39    service: S,40    header_value: Option<HeaderValue>,41}4243impl<S, B> Service<ServiceRequest> for CacheControlMiddleware<S>44where45    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,46    S::Future: 'static,47    B: 'static,48{49    type Response = ServiceResponse<B>;50    type Error = Error;51    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;5253    forward_ready!(service);5455    fn call(&self, req: ServiceRequest) -> Self::Future {56        let is_asset = req.path().starts_with("/assets/");57        let header_value = self.header_value.clone();58        let fut = self.service.call(req);59        Box::pin(async move {60            let mut res = fut.await?;61            // HTML pages can contain personalized content and configuration-dependent62            // links, so they must not be retained by browser or intermediary caches.63            // Static assets set their own (long-lived) cache policy in the asset handler.64            if is_asset {65                if let Some(value) = header_value {66                    res.headers_mut().insert(CACHE_CONTROL, value);67                }68            } else {69                res.headers_mut()70                    .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));71            }72            Ok(res)73        })74    }75}7677#[cfg(test)]78mod tests {79    use super::*;80    use actix_web::{App, HttpResponse, http::header::HeaderValue, test};8182    #[actix_web::test]83    async fn pages_are_not_cached_but_asset_policy_is_preserved() {84        let app = test::init_service(85            App::new()86                .wrap(CacheControl::new(Some(HeaderValue::from_static(87                    "public, max-age=31536000, immutable",88                ))))89                .route(90                    "/login",91                    actix_web::web::get().to(|| async { HttpResponse::Ok().finish() }),92                )93                .route(94                    "/assets/app.css",95                    actix_web::web::get().to(|| async {96                        HttpResponse::Ok()97                            .insert_header((CACHE_CONTROL, "public, max-age=31536000, immutable"))98                            .finish()99                    }),100                ),101        )102        .await;103104        let page =105            test::call_service(&app, test::TestRequest::get().uri("/login").to_request()).await;106        assert_eq!(page.headers().get(CACHE_CONTROL).unwrap(), "no-store");107108        let asset = test::call_service(109            &app,110            test::TestRequest::get().uri("/assets/app.css").to_request(),111        )112        .await;113        assert_eq!(114            asset.headers().get(CACHE_CONTROL).unwrap(),115            "public, max-age=31536000, immutable"116        );117    }118}