Skip to content

Commit

Permalink
Fix tower_http clippy warning (#125)
Browse files Browse the repository at this point in the history
  • Loading branch information
mondeja authored Aug 16, 2024
1 parent 7b10bae commit 6adff72
Showing 1 changed file with 28 additions and 17 deletions.
45 changes: 28 additions & 17 deletions examples/ssr-demo/src/fileserv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,52 @@ use axum::response::Response as AxumResponse;
use axum::{
body::Body,
extract::State,
http::{Request, Response, StatusCode, Uri},
http::{Request, Response, StatusCode},
response::IntoResponse,
};
use leptos::*;
use std::convert::Infallible;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use tower_http::services::{fs::ServeFileSystemResponseBody, ServeDir};

pub async fn file_and_error_handler(
uri: Uri,
State(options): State<LeptosOptions>,
req: Request<Body>,
) -> AxumResponse {
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
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(req).await.into_response()
handler(Request::from_parts(parts, body))
.await
.into_response()
}
}

async fn get_static_file(uri: Uri, root: &str) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder()
.uri(uri.clone())
.body(Body::empty())
.unwrap();
async fn get_static_file(
request: Request<Body>,
root: &str,
) -> Result<Response<ServeFileSystemResponseBody>, Infallible> {
// `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.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
ServeDir::new(root)
.precompressed_gzip()
.precompressed_br()
.oneshot(request)
.await
}

0 comments on commit 6adff72

Please sign in to comment.