From e55565cb3841bf17cf7b8a5e5cf84e59e4372e11 Mon Sep 17 00:00:00 2001 From: Owen Jacobson Date: Wed, 9 Oct 2024 22:52:42 -0400 Subject: Normalize `not found` errors a bit. --- src/ui.rs | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) (limited to 'src/ui.rs') diff --git a/src/ui.rs b/src/ui.rs index bba01cc..18dd049 100644 --- a/src/ui.rs +++ b/src/ui.rs @@ -1,38 +1,60 @@ use axum::{ extract::Path, http::{header, StatusCode}, - response::IntoResponse, + response::{IntoResponse, Response}, routing::get, Router, }; +use mime_guess::Mime; +use rust_embed::EmbeddedFile; #[derive(rust_embed::Embed)] #[folder = "hi-ui/build"] struct Assets; +pub fn router() -> Router +where + S: Clone + Send + Sync + 'static, +{ + Router::new() + .route("/*path", get(asset)) + .route("/", get(root)) +} + +async fn asset(Path(path): Path) -> Result> { + let mime = mime_guess::from_path(&path).first_or_octet_stream(); + + Assets::get(&path) + .map(|file| Asset(mime, file)) + .ok_or(NotFound(format!("not found: {path}"))) +} + async fn root() -> impl IntoResponse { asset(Path(String::from("index.html"))).await } -async fn asset(Path(path): Path) -> impl IntoResponse { - let mime = mime_guess::from_path(&path).first_or_octet_stream(); +struct Asset(Mime, EmbeddedFile); - match Assets::get(&path) { - Some(file) => ( +impl IntoResponse for Asset { + fn into_response(self) -> Response { + let Self(mime, file) = self; + ( StatusCode::OK, [(header::CONTENT_TYPE, mime.as_ref())], file.data, ) - .into_response(), - None => (StatusCode::NOT_FOUND, "").into_response(), + .into_response() } } -pub fn router() -> Router +struct NotFound(pub E); + +impl IntoResponse for NotFound where - S: Clone + Send + Sync + 'static, + E: IntoResponse, { - Router::new() - .route("/*path", get(asset)) - .route("/", get(root)) + fn into_response(self) -> Response { + let Self(response) = self; + (StatusCode::NOT_FOUND, response).into_response() + } } -- cgit v1.2.3