Skip to content

Commit 52145c4

Browse files
authored
Merge pull request #768 from skade/cache-header
Set cache headers on all statics
2 parents c21b716 + 6d76249 commit 52145c4

File tree

2 files changed

+51
-4
lines changed

2 files changed

+51
-4
lines changed

src/caching.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
use rocket::http::hyper::header::{CacheControl, CacheDirective};
2+
use rocket::request::Request;
3+
use rocket::response::{self, Responder};
4+
5+
pub struct Cached<R> {
6+
inner: R,
7+
directives: Vec<CacheDirective>,
8+
}
9+
10+
impl<'r, R> Responder<'r> for Cached<R>
11+
where
12+
R: Responder<'r>,
13+
{
14+
fn respond_to(self, req: &Request) -> response::Result<'r> {
15+
let Cached { inner, directives } = self;
16+
inner.respond_to(req).map(|mut res| {
17+
res.set_header(CacheControl(directives));
18+
res
19+
})
20+
}
21+
}
22+
23+
pub trait Caching
24+
where
25+
Self: Sized,
26+
{
27+
fn cached(self, directives: Vec<CacheDirective>) -> Cached<Self>;
28+
}
29+
30+
impl<'r, R> Caching for R
31+
where
32+
R: Responder<'r>,
33+
{
34+
fn cached(self, directives: Vec<CacheDirective>) -> Cached<Self> {
35+
Cached {
36+
inner: self,
37+
directives: directives,
38+
}
39+
}
40+
}

src/main.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ extern crate regex;
2323
extern crate handlebars;
2424

2525
mod cache;
26+
mod caching;
2627
mod category;
2728
mod headers;
2829
mod i18n;
@@ -56,7 +57,9 @@ use sass_rs::{compile_file, Options};
5657

5758
use category::Category;
5859

60+
use caching::{Cached, Caching};
5961
use i18n::{I18NHelper, SupportedLocale, TeamHelper};
62+
use rocket::http::hyper::header::CacheDirective;
6063

6164
lazy_static! {
6265
static ref ASSETS: AssetFiles = {
@@ -137,13 +140,17 @@ fn components_locale(locale: SupportedLocale, _file: PathBuf) -> Template {
137140
}
138141

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

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

149156
#[get("/")]

0 commit comments

Comments
 (0)