From cccafbeb9771b16338becafc0d389f5d1ae8e99f Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Sat, 12 Nov 2022 10:24:01 +0100 Subject: [PATCH] axum-server: Show User-Agent: --- axum-server/Cargo.toml | 2 +- axum-server/src/main.rs | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) 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)); -- 2.39.5