From: Martin Pitt Date: Sat, 12 Nov 2022 09:24:01 +0000 (+0100) Subject: axum-server: Show User-Agent: X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=cccafbeb9771b16338becafc0d389f5d1ae8e99f;p=learn-rust.git axum-server: Show User-Agent: --- diff --git a/axum-server/Cargo.toml b/axum-server/Cargo.toml index fc59ab7..978ee06 100644 --- a/axum-server/Cargo.toml +++ b/axum-server/Cargo.toml @@ -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"] } diff --git a/axum-server/src/main.rs b/axum-server/src/main.rs index 1225f67..3212d3f 100644 --- a/axum-server/src/main.rs +++ b/axum-server/src/main.rs @@ -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) -> impl response::IntoResponse { - (StatusCode::OK, format!("Hello {}", name)) +async fn hello(Path(name): Path, user_agent: Option>) -> 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));