use actix_web::Error;
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
use actix_web::http::header::{CACHE_CONTROL, HeaderValue};
use std::future::{Future, Ready, ready};
use std::pin::Pin;
#[derive(Clone, Debug, Default)]
pub struct CacheControl {
header_value: Option<HeaderValue>,
}
impl CacheControl {
pub fn new(header_value: Option<HeaderValue>) -> Self {
Self { header_value }
}
}
impl<S, B> Transform<S, ServiceRequest> for CacheControl
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type InitError = ();
type Transform = CacheControlMiddleware<S>;
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
ready(Ok(CacheControlMiddleware {
service,
header_value: self.header_value.clone(),
}))
}
}
pub struct CacheControlMiddleware<S> {
service: S,
header_value: Option<HeaderValue>,
}
impl<S, B> Service<ServiceRequest> for CacheControlMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
S::Future: 'static,
B: 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
forward_ready!(service);
fn call(&self, req: ServiceRequest) -> Self::Future {
let is_asset = req.path().starts_with("/assets/");
let header_value = self.header_value.clone();
let fut = self.service.call(req);
Box::pin(async move {
let mut res = fut.await?;
// HTML pages can contain personalized content and configuration-dependent
// links, so they must not be retained by browser or intermediary caches.
// Static assets set their own (long-lived) cache policy in the asset handler.
if is_asset {
if let Some(value) = header_value {
res.headers_mut().insert(CACHE_CONTROL, value);
}
} else {
res.headers_mut()
.insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
}
Ok(res)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use actix_web::{App, HttpResponse, http::header::HeaderValue, test};
#[actix_web::test]
async fn pages_are_not_cached_but_asset_policy_is_preserved() {
let app = test::init_service(
App::new()
.wrap(CacheControl::new(Some(HeaderValue::from_static(
"public, max-age=31536000, immutable",
))))
.route(
"/login",
actix_web::web::get().to(|| async { HttpResponse::Ok().finish() }),
)
.route(
"/assets/app.css",
actix_web::web::get().to(|| async {
HttpResponse::Ok()
.insert_header((CACHE_CONTROL, "public, max-age=31536000, immutable"))
.finish()
}),
),
)
.await;
let page =
test::call_service(&app, test::TestRequest::get().uri("/login").to_request()).await;
assert_eq!(page.headers().get(CACHE_CONTROL).unwrap(), "no-store");
let asset = test::call_service(
&app,
test::TestRequest::get().uri("/assets/app.css").to_request(),
)
.await;
assert_eq!(
asset.headers().get(CACHE_CONTROL).unwrap(),
"public, max-age=31536000, immutable"
);
}
}