plcom: cache all GET requests resulting in 200 ok

This commit is contained in:
Philippe Loctaux 2024-11-19 22:56:17 +01:00
parent 2673c183a5
commit 3471ccdfbf

View file

@ -1,20 +1,16 @@
use rocket::fairing::{self, Fairing};
use rocket::http::{ContentType, Header};
use rocket::http::{Header, Method, Status};
use rocket::{Request, Response};
#[derive(Debug)]
pub struct CacheControl {
duration_secs: u32,
types: Vec<ContentType>,
routes: Vec<&'static str>,
}
impl Default for CacheControl {
fn default() -> Self {
CacheControl {
duration_secs: 60 * 60, // 60 secs * 60 minutes
types: vec![ContentType::HTML, ContentType::CSS, ContentType::JavaScript],
routes: vec!["/wallpapers", "/pub", "/images", "/icons"],
}
}
}
@ -29,25 +25,8 @@ impl Fairing for CacheControl {
}
async fn on_response<'r>(&self, request: &'r Request<'_>, response: &mut Response<'r>) {
let mut should_cache = false;
// Check if content type matches
if let Some(content_type) = response.content_type() {
if self.types.contains(&content_type) {
println!("going to cache {:?}", content_type);
should_cache = true;
}
}
// TODO: make sure if it is either
// Check if route matches
self.routes
.iter()
.filter(|s| request.uri().path().starts_with(*s))
.for_each(|_| should_cache = true);
if should_cache {
// Aggressive caching
if request.method() == Method::Get && response.status() == Status::Ok {
response.set_header(Header::new(
"Cache-Control",
format!("public, max-age={}", self.duration_secs),