From c9927542defc4cf63e714aef077c84598e48ab00 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sat, 12 Nov 2022 08:35:28 +0100 Subject: [PATCH] axum-server: Serve single static file --- axum-server/Cargo.toml | 2 +- axum-server/src/main.rs | 14 +++++++++++--- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/axum-server/Cargo.toml b/axum-server/Cargo.toml index 206a653..fc59ab7 100644 --- a/axum-server/Cargo.toml +++ b/axum-server/Cargo.toml @@ -9,6 +9,6 @@ edition = "2021" axum = "0.5" tokio = { version = "1", features = ["full"] } tower = "0.4" -tower-http = { version = "0.3", features = ["trace"] } +tower-http = { version = "0.3", features = ["trace", "fs"] } tracing = "0.1" tracing-subscriber = "0.3" diff --git a/axum-server/src/main.rs b/axum-server/src/main.rs index aa2a263..1225f67 100644 --- a/axum-server/src/main.rs +++ b/axum-server/src/main.rs @@ -1,12 +1,14 @@ +use std::io; + use axum::{ - routing::{get}, + routing::{get, get_service}, extract::Path, - http, + http::{StatusCode}, response, Router}; async fn hello(Path(name): Path) -> impl response::IntoResponse { - (http::StatusCode::OK, format!("Hello {}", name)) + (StatusCode::OK, format!("Hello {}", name)) } #[tokio::main] @@ -14,6 +16,12 @@ async fn main() { tracing_subscriber::fmt::init(); let app = Router::new() .route("/hello/:name", get(hello)) + .route("/static", + get_service(tower_http::services::ServeFile::new("Cargo.toml").precompressed_gzip()) + .handle_error(|e: io::Error| async move { + (StatusCode::INTERNAL_SERVER_ERROR, format!("Unhandled internal error: {}", e)) + }) + ) .layer( tower::ServiceBuilder::new() .layer(tower_http::trace::TraceLayer::new_for_http()) -- 2.39.2