From 6bd0bedce1ffe2fade06f767f209edd0b571e6c6 Mon Sep 17 00:00:00 2001 From: Nico Burns Date: Sun, 1 May 2022 23:44:50 +0100 Subject: [PATCH] Add hash query parameter to CSS file URL --- Cargo.lock | 10 ++++++++++ Cargo.toml | 3 +++ src/templates.rs | 14 ++++++++++++++ templates/base.html | 2 +- 4 files changed, 28 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 5f24344..4f6b888 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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" diff --git a/Cargo.toml b/Cargo.toml index 2ed1e03..6b1f523 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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] diff --git a/src/templates.rs b/src/templates.rs index e5f71f5..bd34ac4 100644 --- a/src/templates.rs +++ b/src/templates.rs @@ -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 = Lazy::new(|| { let mut tera = match Tera::new("templates/**/*.html") { @@ -9,6 +13,16 @@ pub(crate) static TERA: Lazy = 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"]); diff --git a/templates/base.html b/templates/base.html index c76ac00..56f08e1 100644 --- a/templates/base.html +++ b/templates/base.html @@ -3,7 +3,7 @@ {% block head %} - + {% block title %}Home{% endblock title %} - Blessed.rs {% endblock head %}