From 57fd838e10a6cdd6d7ee3f54a88104a0d9e74711 Mon Sep 17 00:00:00 2001 From: Ethan Girouard Date: Fri, 1 Mar 2024 14:50:42 -0500 Subject: [PATCH] Add file and error handler --- src/fileserv.rs | 40 ++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 1 + src/main.rs | 2 ++ 3 files changed, 43 insertions(+) create mode 100644 src/fileserv.rs diff --git a/src/fileserv.rs b/src/fileserv.rs new file mode 100644 index 0000000..acc1635 --- /dev/null +++ b/src/fileserv.rs @@ -0,0 +1,40 @@ +use cfg_if::cfg_if; + +cfg_if! { if #[cfg(feature = "ssr")] { + use axum::{ + body::{boxed, Body, BoxBody}, + extract::State, + response::IntoResponse, + http::{Request, Response, StatusCode, Uri}, + }; + use axum::response::Response as AxumResponse; + use tower::ServiceExt; + use tower_http::services::ServeDir; + use leptos::*; + use crate::app::App; + + pub async fn file_and_error_handler(uri: Uri, State(options): State, req: Request) -> AxumResponse { + let root = options.site_root.clone(); + let res = get_static_file(uri.clone(), &root).await.unwrap(); + + if res.status() == StatusCode::OK { + res.into_response() + } else { + let handler = leptos_axum::render_app_to_stream(options.to_owned(), move || view!{}); + handler(req).await.into_response() + } + } + + async fn get_static_file(uri: Uri, root: &str) -> Result, (StatusCode, String)> { + let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap(); + // `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot` + // This path is relative to the cargo root + match ServeDir::new(root).oneshot(req).await { + Ok(res) => Ok(res.map(boxed)), + Err(err) => Err(( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Something went wrong: {err}"), + )), + } + } +}} diff --git a/src/lib.rs b/src/lib.rs index 95ab806..28a9044 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,6 +10,7 @@ pub mod models; pub mod pages; pub mod users; pub mod search; +pub mod fileserv; use cfg_if::cfg_if; cfg_if! { diff --git a/src/main.rs b/src/main.rs index e474dd0..246bc78 100644 --- a/src/main.rs +++ b/src/main.rs @@ -18,6 +18,7 @@ async fn main() { use leptos::*; use leptos_axum::{generate_route_list, LeptosRoutes}; use libretunes::app::*; + use libretunes::fileserv::file_and_error_handler; use dotenv::dotenv; dotenv().ok(); @@ -35,6 +36,7 @@ async fn main() { let app = Router::new() .leptos_routes(&leptos_options, routes, App) + .fallback(file_and_error_handler) .with_state(leptos_options); println!("listening on http://{}", &addr);