ezidam: ability to cache routes as well as types
This commit is contained in:
parent
2054b6835f
commit
bd1530a4e2
1 changed files with 25 additions and 10 deletions
|
|
@ -4,16 +4,18 @@ use rocket::{Build, Request, Response, Rocket};
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct CacheControl {
|
pub struct CacheControl {
|
||||||
max_age: u32,
|
duration_secs: u32,
|
||||||
cache_types: Vec<ContentType>,
|
types: Vec<ContentType>,
|
||||||
|
routes: Vec<&'static str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for CacheControl {
|
impl Default for CacheControl {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
CacheControl {
|
CacheControl {
|
||||||
// 60 secs * 60 minutes
|
// 60 secs * 60 minutes
|
||||||
max_age: 60 * 60,
|
duration_secs: 60 * 60,
|
||||||
cache_types: vec![ContentType::CSS, ContentType::JavaScript],
|
types: vec![ContentType::CSS, ContentType::JavaScript],
|
||||||
|
routes: vec!["/logo"],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -33,14 +35,27 @@ impl Fairing for CacheControl {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
|
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 let Some(content_type) = response.content_type() {
|
||||||
if self.cache_types.contains(&content_type) {
|
if self.types.contains(&content_type) {
|
||||||
|
should_cache = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if route matches
|
||||||
|
self.routes
|
||||||
|
.iter()
|
||||||
|
.filter(|s| request.uri().path().starts_with(*s))
|
||||||
|
.for_each(|_| should_cache = true);
|
||||||
|
|
||||||
|
if should_cache {
|
||||||
response.set_header(Header::new(
|
response.set_header(Header::new(
|
||||||
"Cache-Control",
|
"Cache-Control",
|
||||||
format!("public, max-age={}", self.max_age),
|
format!("public, max-age={}", self.duration_secs),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue