From 7774cfd1f7d6e0d8bcba80b8b2a7b81d9a992cc0 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Sun, 8 May 2022 21:52:34 +0200 Subject: [PATCH] Update static file server example (#1011) --- examples/static-file-server/Cargo.toml | 1 + examples/static-file-server/src/main.rs | 34 ++++++++++++++++--------- 2 files changed, 23 insertions(+), 12 deletions(-) diff --git a/examples/static-file-server/Cargo.toml b/examples/static-file-server/Cargo.toml index d927ec97..9cadd4d3 100644 --- a/examples/static-file-server/Cargo.toml +++ b/examples/static-file-server/Cargo.toml @@ -6,6 +6,7 @@ publish = false [dependencies] axum = { path = "../../axum" } +axum-extra = { path = "../../axum-extra", features = ["spa"] } tokio = { version = "1.0", features = ["full"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/examples/static-file-server/src/main.rs b/examples/static-file-server/src/main.rs index fad45206..1862ecab 100644 --- a/examples/static-file-server/src/main.rs +++ b/examples/static-file-server/src/main.rs @@ -4,8 +4,13 @@ //! cd examples && cargo run -p example-static-file-server //! ``` -use axum::{http::StatusCode, routing::get_service, Router}; -use std::net::SocketAddr; +use axum::{ + http::StatusCode, + response::IntoResponse, + routing::{get, get_service}, + Router, +}; +use std::{io, net::SocketAddr}; use tower_http::{services::ServeDir, trace::TraceLayer}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -19,16 +24,17 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - let app = Router::new() - .nest( - "/static", - get_service(ServeDir::new(".")).handle_error(|error: std::io::Error| async move { - ( - StatusCode::INTERNAL_SERVER_ERROR, - format!("Unhandled internal error: {}", error), - ) - }), - ) + // `SpaRouter` is the easiest way to serve assets at a nested route like `/assets` + // let app = Router::new() + // .route("/foo", get(|| async { "Hi from /foo" })) + // .merge(axum_extra::routing::SpaRouter::new("/assets", ".")) + // .layer(TraceLayer::new_for_http()); + + // for serving assets directly at the root you can use `tower_http::services::ServeDir` + // as the fallback to a `Router` + let app: _ = Router::new() + .route("/foo", get(|| async { "Hi from /foo" })) + .fallback(get_service(ServeDir::new(".")).handle_error(handle_error)) .layer(TraceLayer::new_for_http()); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); @@ -38,3 +44,7 @@ async fn main() { .await .unwrap(); } + +async fn handle_error(_err: io::Error) -> impl IntoResponse { + (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong...") +}