From 9f7b903901acb0cd6ec9cb2146406a92ebf79cab Mon Sep 17 00:00:00 2001 From: Vika Date: Fri, 7 Oct 2022 19:53:04 +0300 Subject: templates: move static assets to the templates crate It makes more sense to keep CSS near the templates, and the client-side JavaScript code too, since it depends on the DOM structure to work. Additionally, the overhead of `include_dir!()` is almost completely mitigated by the fact that this is a separate crate that isn't recompiled often. The linking stage, however, is still expected to take a little bit long. But I doubt it'd be longer than what it was before, since it's the same exact files that get linked into the app. --- kittybox-rs/templates/src/lib.rs | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) (limited to 'kittybox-rs/templates/src/lib.rs') diff --git a/kittybox-rs/templates/src/lib.rs b/kittybox-rs/templates/src/lib.rs index d58e831..5b3a8df 100644 --- a/kittybox-rs/templates/src/lib.rs +++ b/kittybox-rs/templates/src/lib.rs @@ -9,6 +9,37 @@ pub use login::LoginPage; mod mf2; pub use mf2::{Entry, VCard, Feed, Food, POSTS_PER_PAGE}; +pub mod assets { + use axum::response::{IntoResponse, Response}; + use axum::extract::Path; + use axum::http::StatusCode; + use axum::http::header::{CONTENT_TYPE, CACHE_CONTROL}; + + const ASSETS: include_dir::Dir<'static> = include_dir::include_dir!("$OUT_DIR"); + const CACHE_FOR_A_DAY: &str = "max-age=86400"; + + pub async fn statics(Path(path): Path) -> Response { + + let content_type: &'static str = if path.ends_with(".js") { + "application/javascript" + } else if path.ends_with(".css") { + "text/css" + } else if path.ends_with(".html") { + "text/html; charset=\"utf-8\"" + } else { + "application/octet-stream" + }; + + match ASSETS.get_file(path) { + Some(file) => (StatusCode::OK, + [(CONTENT_TYPE, content_type), + (CACHE_CONTROL, CACHE_FOR_A_DAY)], + file.contents()).into_response(), + None => StatusCode::NOT_FOUND.into_response() + } + } +} + #[cfg(test)] mod tests { use faker_rand::en_us::internet::Domain; -- cgit 1.4.1