ezidam: cache for one hour css and js files

This commit is contained in:
Philippe Loctaux 2023-03-07 19:22:44 +01:00
parent 8f951a55d7
commit 2054b6835f
3 changed files with 54 additions and 3 deletions

View file

@ -0,0 +1,46 @@
use rocket::fairing::{self, Fairing};
use rocket::http::{ContentType, Header};
use rocket::{Build, Request, Response, Rocket};
#[derive(Debug)]
pub struct CacheControl {
max_age: u32,
cache_types: Vec<ContentType>,
}
impl Default for CacheControl {
fn default() -> Self {
CacheControl {
// 60 secs * 60 minutes
max_age: 60 * 60,
cache_types: vec![ContentType::CSS, ContentType::JavaScript],
}
}
}
impl CacheControl {
pub fn rocket(rocket_builder: Rocket<Build>) -> Rocket<Build> {
rocket_builder.attach(Self::default())
}
}
#[rocket::async_trait]
impl Fairing for CacheControl {
fn info(&self) -> fairing::Info {
fairing::Info {
name: "Cache Control",
kind: fairing::Kind::Response,
}
}
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
if let Some(content_type) = response.content_type() {
if self.cache_types.contains(&content_type) {
response.set_header(Header::new(
"Cache-Control",
format!("public, max-age={}", self.max_age),
));
}
}
}
}

View file

@ -1,5 +1,6 @@
use rocket::{Build, Rocket};
mod cache;
mod database;
mod error;
mod file_from_bytes;
@ -13,6 +14,7 @@ mod shutdown;
mod tests;
pub fn rocket_setup(rocket_builder: Rocket<Build>) -> Rocket<Build> {
use cache::CacheControl;
use database::Database;
use error::catchers;
use response_timer::ResponseTimer;
@ -22,6 +24,9 @@ pub fn rocket_setup(rocket_builder: Rocket<Build>) -> Rocket<Build> {
// Response timer
let rocket_builder = ResponseTimer::rocket(rocket_builder);
// Cache control
let rocket_builder = CacheControl::rocket(rocket_builder);
// Database
let rocket_builder = Database::rocket(rocket_builder);

View file

@ -1,7 +1,7 @@
// Code stolen from https://crates.io/crates/rocket-response-time
// Copyright Thomas Parsley <info@thomasparsley.cz>, MIT License
use rocket::fairing::{Fairing, Kind};
use rocket::fairing::{self, Fairing, Kind};
use rocket::{Build, Request, Rocket};
pub struct ResponseTimer {}
@ -14,8 +14,8 @@ impl ResponseTimer {
#[rocket::async_trait]
impl Fairing for ResponseTimer {
fn info(&self) -> rocket::fairing::Info {
rocket::fairing::Info {
fn info(&self) -> fairing::Info {
fairing::Info {
name: "ResponseTimer",
kind: Kind::Request | Kind::Response,
}