From 70bb0691d30e7c7a810801cf953c7af297dd021b Mon Sep 17 00:00:00 2001 From: Fries Date: Tue, 11 Jul 2023 02:37:31 -0700 Subject: [PATCH] implement a CachedResponse Responder struct this adds a Cache-Control header to existing responses so they can be cached in the browser. cache busting means this cache can be immutable as if the file changes, the filename changes, so the browser will get new files. --- src/assets/routes.rs | 52 ++++++++++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 9 deletions(-) diff --git a/src/assets/routes.rs b/src/assets/routes.rs index 35fa391..db2be30 100644 --- a/src/assets/routes.rs +++ b/src/assets/routes.rs @@ -1,5 +1,9 @@ use super::{files::get_file_wrapper, templates::ErrorTemplate}; -use rocket::{http::Status, response::content::RawCss}; +use rocket::{ + http::{Header, Status}, + response::{self, content::RawCss, Responder}, + Response, +}; use std::borrow::Cow; #[derive(Responder)] @@ -15,8 +19,32 @@ pub struct ErrorTemplateResponder<'a> { template: ErrorTemplate<'a>, } +pub struct CachedResponse { + inner: T, +} + +impl<'r, T> Responder<'r, 'static> for CachedResponse +where + T: Responder<'r, 'static>, +{ + fn respond_to(self, request: &'r rocket::Request<'_>) -> response::Result<'static> { + Response::build_from(self.inner.respond_to(request)?) + .header(Header::new("Cache-Control", "max-age=31536000, immutable")) + .ok() + } +} + +impl<'r, T> From for CachedResponse +where + T: Responder<'r, 'static>, +{ + fn from(value: T) -> Self { + CachedResponse { inner: value } + } +} + #[get("/css/