Skip to content

Commit

Permalink
fix: restore fileserv2
Browse files Browse the repository at this point in the history
  • Loading branch information
dancixx committed Sep 3, 2024
1 parent 2036635 commit 6f620fe
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 1 deletion.
60 changes: 60 additions & 0 deletions src/fileserv.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use crate::app::App;
use axum::response::Response as AxumResponse;
use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode},
response::IntoResponse,
};
use leptos::*;
use tower::ServiceExt;
use tower_http::services::ServeDir;

pub async fn file_and_error_handler(
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
let root = options.site_root.clone();
let (parts, body) = req.into_parts();

let mut static_parts = parts.clone();
static_parts.headers.clear();
if let Some(encodings) = parts.headers.get("accept-encoding") {
static_parts
.headers
.insert("accept-encoding", encodings.clone());
}

let res = get_static_file(Request::from_parts(static_parts, Body::empty()), &root)
.await
.unwrap();

if res.status() == StatusCode::OK {
res.into_response()
} else {
let handler = leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(Request::from_parts(parts, body))
.await
.into_response()
}
}

async fn get_static_file(
request: Request<Body>,
root: &str,
) -> Result<Response<Body>, (StatusCode, String)> {
// `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)
.precompressed_gzip()
.precompressed_br()
.oneshot(request)
.await
{
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Error serving files: {err}"),
)),
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
pub mod app;
pub mod context;
pub mod exercises;
#[cfg(feature = "ssr")]
pub mod fileserv;
pub mod instruction;
#[cfg(feature = "ssr")]
pub mod redirect;
Expand Down
3 changes: 2 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ async fn main() {
use chrono::{Duration, Utc};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use tryrust::fileserv::file_and_error_handler;
use std::fs;
use tokio_cron_scheduler::{Job, JobScheduler};
use tower_http::trace::TraceLayer;
Expand Down Expand Up @@ -64,7 +65,7 @@ async fn main() {
let app = Router::new()
.leptos_routes(&leptos_options, routes, App)
// TODO: new version in v.0.7.0
.fallback((|| (StatusCode::NOT_FOUND, "Not Found"))())
.fallback(file_and_error_handler)
.layer(
tower::ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
Expand Down

0 comments on commit 6f620fe

Please sign in to comment.