simplify registering static routes

This commit is contained in:
mat 2024-07-03 02:49:07 +00:00
parent a0e8c47a6f
commit 130d976d45

View File

@ -21,6 +21,24 @@ use tracing::info;
use crate::config::Config; 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) { pub async fn run(config: Config) {
let bind_addr = config.bind; let bind_addr = config.bind;
@ -42,45 +60,6 @@ pub async fn run(config: Config) {
.route("/search", get(search::get)) .route("/search", get(search::get))
.route("/settings", get(settings::get)) .route("/settings", get(settings::get))
.route("/settings", post(settings::post)) .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("/opensearch.xml", get(opensearch::route))
.route("/autocomplete", get(autocomplete::route)) .route("/autocomplete", get(autocomplete::route))
.route("/image-proxy", get(image_proxy::route)) .route("/image-proxy", get(image_proxy::route))
@ -89,6 +68,15 @@ pub async fn run(config: Config) {
config_middleware, config_middleware,
)) ))
.with_state(config); .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}"); info!("Listening on http://{bind_addr}");
@ -101,6 +89,15 @@ pub async fn run(config: Config) {
.unwrap(); .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( async fn config_middleware(
State(config): State<Arc<Config>>, State(config): State<Arc<Config>>,
cookies: CookieJar, cookies: CookieJar,