]> piware.de Git - learn-rust.git/commitdiff
axum-server: Serve single static file
authorMartin Pitt <martin@piware.de>
Sat, 12 Nov 2022 07:35:28 +0000 (08:35 +0100)
committerMartin Pitt <martin@piware.de>
Sat, 12 Nov 2022 07:35:28 +0000 (08:35 +0100)
axum-server/Cargo.toml
axum-server/src/main.rs

index 206a653f505fbf558bf997340c66922a4479cff0..fc59ab7c2ca7ceb1c7c43bbe27a62df7093e8631 100644 (file)
@@ -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"
index aa2a26337a2551d44d1a77d3cc598214d97fffa0..1225f67614184b5b34cc0bb3a9703bb19d225433 100644 (file)
@@ -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<String>) -> 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())