Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix tower_http clippy warning #125

Merged
merged 1 commit into from
Aug 16, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}