about summary refs log tree commit diff
path: root/kittybox-rs/templates/src/lib.rs
diff options
context:
space:
mode:
authorVika <vika@fireburn.ru>2022-10-07 19:53:04 +0300
committerVika <vika@fireburn.ru>2022-10-07 19:53:04 +0300
commit9f7b903901acb0cd6ec9cb2146406a92ebf79cab (patch)
treec7a45f69d2d59621365494dc2d3657848390b61d /kittybox-rs/templates/src/lib.rs
parent6cb479acc61ab19f655cedd878283b214e352a3d (diff)
downloadkittybox-9f7b903901acb0cd6ec9cb2146406a92ebf79cab.tar.zst
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.
Diffstat (limited to 'kittybox-rs/templates/src/lib.rs')
-rw-r--r--kittybox-rs/templates/src/lib.rs31
1 files changed, 31 insertions, 0 deletions
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<String>) -> 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;