Skip to content
Myr

main.rs

This file

Path

examples/static-file-server/src/main.rs

124 lines · 4.2 KiB · Rust

Last changed by

examples: fix `using_serve_dir_with_assets_fallback` to not expose assets at root (#3762)Zelysbefore adoptiona480d71

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-static-file-server5//! ```67use axum::{8    extract::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router,9};10use std::net::SocketAddr;11use tower::ServiceExt;12use tower_http::{13    services::{ServeDir, ServeFile},14    set_status::SetStatus,15    trace::TraceLayer,16};17use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1819#[tokio::main]20async fn main() {21    tracing_subscriber::registry()22        .with(23            tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {24                format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into()25            }),26        )27        .with(tracing_subscriber::fmt::layer())28        .init();2930    tokio::join!(31        serve(using_serve_dir(), 3001),32        serve(using_serve_dir_with_assets_fallback(), 3002),33        serve(using_serve_dir_only_from_root_via_fallback(), 3003),34        serve(using_serve_dir_with_handler_as_service(), 3004),35        serve(two_serve_dirs(), 3005),36        serve(calling_serve_dir_from_a_handler(), 3006),37        serve(using_serve_file_from_a_route(), 3307),38    );39}4041fn using_serve_dir() -> Router {42    // serve the file in the "assets" directory under `/assets`43    Router::new().nest_service("/assets", ServeDir::new("assets"))44}4546fn using_serve_dir_with_assets_fallback() -> Router {47    // `ServeDir` allows setting a fallback if an asset is not found48    // so with this `GET /assets/doesnt-exist.jpg` will return `index.html`49    // rather than a 404.50    // The `fallback_service` ensures that all other paths (the standard51    // SPA pattern) also return `index.html`. We wrap it in `SetStatus` so52    // the response uses 404 instead of 200 -- the path wasn't found, the SPA53    // just handles routing client-side.54    let index_html = SetStatus::new(ServeFile::new("assets/index.html"), StatusCode::NOT_FOUND);55    let serve_dir = ServeDir::new("assets").not_found_service(index_html.clone());5657    Router::new()58        .route("/foo", get(|| async { "Hi from /foo" }))59        .nest_service("/assets", serve_dir)60        .fallback_service(index_html)61}6263fn using_serve_dir_only_from_root_via_fallback() -> Router {64    // you can also serve the assets directly from the root (not nested under `/assets`)65    // by only setting a `ServeDir` as the fallback66    let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html"));6768    Router::new()69        .route("/foo", get(|| async { "Hi from /foo" }))70        .fallback_service(serve_dir)71}7273fn using_serve_dir_with_handler_as_service() -> Router {74    async fn handle_404() -> (StatusCode, &'static str) {75        (StatusCode::NOT_FOUND, "Not found")76    }7778    // you can convert handler function to service79    let service = handle_404.into_service();8081    let serve_dir = ServeDir::new("assets").not_found_service(service);8283    Router::new()84        .route("/foo", get(|| async { "Hi from /foo" }))85        .fallback_service(serve_dir)86}8788fn two_serve_dirs() -> Router {89    // you can also have two `ServeDir`s nested at different paths90    let serve_dir_from_assets = ServeDir::new("assets");91    let serve_dir_from_dist = ServeDir::new("dist");9293    Router::new()94        .nest_service("/assets", serve_dir_from_assets)95        .nest_service("/dist", serve_dir_from_dist)96}9798#[allow(clippy::let_and_return)]99fn calling_serve_dir_from_a_handler() -> Router {100    // via `tower::Service::call`, or more conveniently `tower::ServiceExt::oneshot` you can101    // call `ServeDir` yourself from a handler102    Router::new().nest_service(103        "/foo",104        get(|request: Request| async {105            let service = ServeDir::new("assets");106            let result = service.oneshot(request).await;107            result108        }),109    )110}111112fn using_serve_file_from_a_route() -> Router {113    Router::new().route_service("/foo", ServeFile::new("assets/index.html"))114}115116#[cfg(test)]117mod tests;118119async fn serve(app: Router, port: u16) {120    let addr = SocketAddr::from(([127, 0, 0, 1], port));121    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();122    tracing::debug!("listening on {}", listener.local_addr().unwrap());123    axum::serve(listener, app.layer(TraceLayer::new_for_http())).await;124}