feat: default cache-control headers for web assets
Diff
src/control_headers.rs | 41 +++++++++++++++++++++++++++++++++++++++++
src/handler.rs | 13 +++++++++++--
src/lib.rs | 1 +
3 files changed, 53 insertions(+), 2 deletions(-)
@@ -0,0 +1,41 @@
use headers::{CacheControl, HeaderMapExt};
use hyper::{Body, Response};
const CACHE_EXT_ONE_HOUR: [&str; 4] = ["atom", "json", "rss", "xml"];
const CACHE_EXT_ONE_YEAR: [&str; 30] = [
"bmp", "bz2", "css", "doc", "gif", "gz", "htc", "ico", "jpeg", "jpg", "js", "map", "mjs",
"mp3", "mp4", "ogg", "ogv", "pdf", "png", "rar", "rtf", "tar", "tgz", "wav", "weba", "webm",
"webp", "woff", "woff2", "zip",
];
pub fn with_cache_control(ext: &str, resp: &mut Response<Body>) {
let mut max_age = 60 * 60 * 24_u64;
if CACHE_EXT_ONE_HOUR
.iter()
.any(|x| ext.ends_with(&[".", *x].concat()))
{
max_age = 60 * 60;
} else if CACHE_EXT_ONE_YEAR
.iter()
.any(|x| ext.ends_with(&[".", *x].concat()))
{
max_age = 60 * 60 * 24 * 365;
}
let cache_control = CacheControl::new()
.with_public()
.with_max_age(duration_from_secs(max_age));
resp.headers_mut().typed_insert(cache_control);
}
fn duration_from_secs(secs: u64) -> std::time::Duration {
std::time::Duration::from_secs(std::cmp::min(secs, u32::MAX as u64))
}
@@ -1,7 +1,7 @@
use hyper::{Body, Request, Response};
use std::path::Path;
use crate::{compression, static_files};
use crate::{compression, control_headers, static_files};
use crate::{error::Result, error_page};
@@ -10,7 +10,16 @@ pub async fn handle_request(base: &Path, req: &Request<Body>) -> Result<Response
let method = req.method();
match static_files::handle_request(method, headers, base, req.uri().path()).await {
Ok(resp) => compression::auto(method, headers, resp),
Ok(resp) => {
let mut resp = compression::auto(method, headers, resp)?;
let ext = req.uri().path().to_lowercase();
control_headers::with_cache_control(&ext, &mut resp);
Ok(resp)
}
Err(status) => error_page::get_error_response(method, &status),
}
}
@@ -5,6 +5,7 @@ extern crate anyhow;
pub mod compression;
pub mod config;
pub mod control_headers;
pub mod error_page;
pub mod handler;
pub mod helpers;