From 130d976d45bbc23fb0564e7d9ee111b31f2c553c Mon Sep 17 00:00:00 2001 From: mat Date: Wed, 3 Jul 2024 02:49:07 +0000 Subject: [PATCH] simplify registering static routes --- src/web/mod.rs | 75 ++++++++++++++++++++++++-------------------------- 1 file changed, 36 insertions(+), 39 deletions(-) diff --git a/src/web/mod.rs b/src/web/mod.rs index e544e25..7bb6600 100644 --- a/src/web/mod.rs +++ b/src/web/mod.rs @@ -21,6 +21,24 @@ use tracing::info; use crate::config::Config; +macro_rules! register_static_routes { + ( $app:ident, $( $x:expr ),* ) => { + { + $( + let $app = $app.route( + concat!("/", $x), + static_route( + include_str!(concat!("assets/", $x)), + guess_mime_type($x) + ), + ); + )* + + $app + } + }; +} + pub async fn run(config: Config) { let bind_addr = config.bind; @@ -42,45 +60,6 @@ pub async fn run(config: Config) { .route("/search", get(search::get)) .route("/settings", get(settings::get)) .route("/settings", post(settings::post)) - .route( - "/style.css", - static_route(include_str!("assets/style.css"), "text/css; charset=utf-8"), - ) - .route( - "/script.js", - static_route( - include_str!("assets/script.js"), - "text/javascript; charset=utf-8", - ), - ) - .route( - "/robots.txt", - static_route( - include_str!("assets/robots.txt"), - "text/plain; charset=utf-8", - ), - ) - .route( - "/themes/catppuccin-mocha.css", - static_route( - include_str!("assets/themes/catppuccin-mocha.css"), - "text/css; charset=utf-8", - ), - ) - .route( - "/themes/nord-bluish.css", - static_route( - include_str!("assets/themes/nord-bluish.css"), - "text/css; charset=utf-8", - ), - ) - .route( - "/themes/discord.css", - static_route( - include_str!("assets/themes/discord.css"), - "text/css; charset=utf-8", - ), - ) .route("/opensearch.xml", get(opensearch::route)) .route("/autocomplete", get(autocomplete::route)) .route("/image-proxy", get(image_proxy::route)) @@ -89,6 +68,15 @@ pub async fn run(config: Config) { config_middleware, )) .with_state(config); + let app = register_static_routes![ + app, + "style.css", + "script.js", + "robots.txt", + "themes/catppuccin-mocha.css", + "themes/nord-bluish.css", + "themes/discord.css" + ]; info!("Listening on http://{bind_addr}"); @@ -101,6 +89,15 @@ pub async fn run(config: Config) { .unwrap(); } +fn guess_mime_type(path: &str) -> &'static str { + match path.rsplit('.').next() { + Some("css") => "text/css; charset=utf-8", + Some("js") => "text/javascript; charset=utf-8", + Some("txt") => "text/plain; charset=utf-8", + _ => "text/plain; charset=utf-8", + } +} + async fn config_middleware( State(config): State>, cookies: CookieJar,