]> piware.de Git - learn-rust.git/commitdiff
axum-server: Show User-Agent:
authorMartin Pitt <martin@piware.de>
Sat, 12 Nov 2022 09:24:01 +0000 (10:24 +0100)
committerMartin Pitt <martin@piware.de>
Sat, 12 Nov 2022 09:24:01 +0000 (10:24 +0100)
axum-server/Cargo.toml
axum-server/src/main.rs

index fc59ab7c2ca7ceb1c7c43bbe27a62df7093e8631..978ee0601206492e21b25c60af632a64f68ffd04 100644 (file)
@@ -6,7 +6,7 @@ edition = "2021"
 # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
 
 [dependencies]
-axum = "0.5"
+axum = { version = "0.5", features = ["headers"] }
 tokio = { version = "1", features = ["full"] }
 tower = "0.4"
 tower-http = { version = "0.3", features = ["trace", "fs"] }
index 1225f67614184b5b34cc0bb3a9703bb19d225433..3212d3f250962e2f422419951e1ce0fd0d355b13 100644 (file)
@@ -2,13 +2,17 @@ use std::io;
 
 use axum::{
     routing::{get, get_service},
-    extract::Path,
+    extract::{Path, TypedHeader},
     http::{StatusCode},
     response,
     Router};
 
-async fn hello(Path(name): Path<String>) -> impl response::IntoResponse {
-    (StatusCode::OK, format!("Hello {}", name))
+async fn hello(Path(name): Path<String>, user_agent: Option<TypedHeader<axum::headers::UserAgent>>) -> impl response::IntoResponse {
+    if let Some(TypedHeader(user_agent)) = user_agent {
+        (StatusCode::OK, format!("Hello {} from {}", name, user_agent))
+    } else {
+        (StatusCode::OK, format!("Hello {}", name))
+    }
 }
 
 #[tokio::main]
@@ -24,7 +28,10 @@ async fn main() {
         )
         .layer(
             tower::ServiceBuilder::new()
-                .layer(tower_http::trace::TraceLayer::new_for_http())
+                .layer(
+                    tower_http::trace::TraceLayer::new_for_http()
+                         .make_span_with(tower_http::trace::DefaultMakeSpan::default().include_headers(true)),
+                )
         );
 
     let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000));