Skip to content

Set cache headers on all statics #768

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions src/caching.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use rocket::http::hyper::header::{CacheControl, CacheDirective};
use rocket::request::Request;
use rocket::response::{self, Responder};

pub struct Cached<R> {
inner: R,
directives: Vec<CacheDirective>,
}

impl<'r, R> Responder<'r> for Cached<R>
where
R: Responder<'r>,
{
fn respond_to(self, req: &Request) -> response::Result<'r> {
let Cached { inner, directives } = self;
inner.respond_to(req).map(|mut res| {
res.set_header(CacheControl(directives));
res
})
}
}

pub trait Caching
where
Self: Sized,
{
fn cached(self, directives: Vec<CacheDirective>) -> Cached<Self>;
}

impl<'r, R> Caching for R
where
R: Responder<'r>,
{
fn cached(self, directives: Vec<CacheDirective>) -> Cached<Self> {
Cached {
inner: self,
directives: directives,
}
}
}
15 changes: 11 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ extern crate regex;
extern crate handlebars;

mod cache;
mod caching;
mod category;
mod headers;
mod i18n;
Expand Down Expand Up @@ -50,7 +51,9 @@ use sass_rs::{compile_file, Options};

use category::Category;

use caching::{Cached, Caching};
use i18n::{I18NHelper, SupportedLocale, TeamHelper};
use rocket::http::hyper::header::CacheDirective;

#[derive(Serialize)]
struct Context<T: ::serde::Serialize> {
Expand Down Expand Up @@ -87,13 +90,17 @@ fn components(_file: PathBuf) -> Template {
}

#[get("/logos/<file..>", rank = 1)]
fn logos(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("static/logos").join(file)).ok()
fn logos(file: PathBuf) -> Option<Cached<NamedFile>> {
NamedFile::open(Path::new("static/logos").join(file))
.ok()
.map(|file| file.cached(vec![CacheDirective::MaxAge(3600)]))
}

#[get("/static/<file..>", rank = 1)]
fn files(file: PathBuf) -> Option<NamedFile> {
NamedFile::open(Path::new("static/").join(file)).ok()
fn files(file: PathBuf) -> Option<Cached<NamedFile>> {
NamedFile::open(Path::new("static/").join(file))
.ok()
.map(|file| file.cached(vec![CacheDirective::MaxAge(3600)]))
}

#[get("/")]
Expand Down