如何在Rust Axum中获取完整请求URI(scheme+authority+path)
我尝试获取包含scheme、authority和path的完整请求URI,先后用两种方式实现,但都只得到路径部分,调用scheme_str()和authority()时返回None,触发unwrap() panic。
尝试一:通过Request实现
use axum::body::Body; use axum::http::Request; use axum::routing::get; use axum::Router; async fn handler(req: Request<Body>) -> &'static str { println!("The request is: {}", req.uri()); println!("The request is: {}", req.uri().scheme_str().unwrap()); println!("The request is: {}", req.uri().authority().unwrap()); "Hello world" } #[tokio::main] async fn main() { let app = Router::new().route("/test", get(handler)); axum::Server::bind(&"0.0.0.0:8080".parse().unwrap()) .serve(app.into_make_service()) .await .unwrap(); }
运行命令:
curl -v "http://localhost:8080/test"
仅打印路径/test,并触发panic:
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:59
尝试二:通过Uri提取器实现
use axum::http::Uri; use axum::routing::get; use axum::Router; async fn handler(uri: Uri) -> &'static str { println!("The request is: {}", uri); println!("The request is: {}", uri.scheme_str().unwrap()); println!("The request is: {}", uri.authority().unwrap()); "Hello world" } #[tokio::main] async fn main() { let app = Router::new().route("/test", get(handler)); axum::Server::bind(&"0.0.0.0:8080".parse().unwrap()) .serve(app.into_make_service()) .await .unwrap(); }
运行相同的curl命令后,同样只得到路径,触发相同panic。
运行环境
- cargo 1.68.0-nightly (2381cbdb4 2022-12-23)
- rustc 1.68.0-nightly (ad8ae0504 2022-12-29)
Cargo.toml依赖
[package] name = "axum_test" version = "0.1.0" edition = "2021" [dependencies] axum = "0.6.10" tokio = { version = "1.26.0", features = ["macros", "rt-multi-thread"] }
内容的提问来源于stack exchange,提问作者mepmerp
相关产品推荐
相关产品推荐

