Add hash query parameter to CSS file URL

This commit is contained in:
Nico Burns 2022-05-01 23:44:50 +01:00
parent 0ef29eea4b
commit 6bd0bedce1
4 changed files with 28 additions and 1 deletions

10
Cargo.lock generated
View file

@ -92,6 +92,7 @@ name = "blessed-rs"
version = "0.1.0"
dependencies = [
"axum",
"fxhash",
"once_cell",
"serde",
"serde_json",
@ -276,6 +277,15 @@ dependencies = [
"pin-utils",
]
[[package]]
name = "fxhash"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c"
dependencies = [
"byteorder",
]
[[package]]
name = "generic-array"
version = "0.12.4"

View file

@ -7,6 +7,7 @@ edition = "2021"
[dependencies]
axum = "0.4.8"
fxhash = "0.2.1"
once_cell = "1.10.0"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0.79"
@ -15,3 +16,5 @@ tokio = { version = "1.17", features = ["full"] }
tower-http = { version = "0.2.5", features = ["fs", "trace"] }
tracing = "0.1.32"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[features]

View file

@ -1,5 +1,9 @@
use tera::Tera;
use once_cell::sync::Lazy;
use fxhash::hash32;
use std::fs::read_to_string;
use std::env::current_dir;
use serde_json::{ Value, Number };
pub(crate) static TERA: Lazy<Tera> = Lazy::new(|| {
let mut tera = match Tera::new("templates/**/*.html") {
@ -9,6 +13,16 @@ pub(crate) static TERA: Lazy<Tera> = Lazy::new(|| {
::std::process::exit(1);
}
};
// Register function to get hash of CSS file. Hash doesn't need to be secure as it is
// purely to prevent the old version of the file being cached when the file it updated
let cwd = current_dir().unwrap();
let index_css_path = { let mut path = cwd.clone(); path.push("static/index.css"); path };
let index_css_contents = read_to_string(index_css_path).unwrap();
let index_css_hash = hash32(&index_css_contents);
let index_css_hash_json_value = Value::Number(Number::from_f64(f64::from(index_css_hash)).unwrap());
tera.register_function("get_index_css_hash", move |_: &_| Ok(index_css_hash_json_value.clone()));
// let mut tera = Tera::default();
// tera.add_raw_template("list.html", include_str!("list.html")).unwrap();
tera.autoescape_on(vec![".html", ".sql"]);

View file

@ -3,7 +3,7 @@
<head>
{% block head %}
<link rel="stylesheet" href="/static/normalize.css" />
<link rel="stylesheet" href="/static/index.css" />
<link rel="stylesheet" href="/static/index.css?{{ get_index_css_hash() }}" />
<title>{% block title %}Home{% endblock title %} - Blessed.rs</title>
{% endblock head %}
</head>