Rust Axum Get Full URI请求

sc4hvdpw  于 2023-06-23  发布在  其他
关注(0)|答案(1)|浏览(119)

尝试获取完整的请求URI(scheme + authority + path)
我找到了讨论:https://github.com/tokio-rs/axum/discussions/1149,它说Request.uri()应该有它。所以我尝试了以下方法:

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",得到:

The request is: /test
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:59

它似乎只包含路径。
我还发现了另一个问题:https://github.com/tokio-rs/axum/discussions/858,这表明axum::http::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 -v "http://localhost:8080/test"

The request is: /test
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:7:53
> cargo -V
cargo 1.68.0-nightly (2381cbdb4 2022-12-23)

> rustc --version
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"] }
tf7tbtn2

tf7tbtn21#

Request中的Uri仅提供path。你可以使用Host extractor

use axum::extract::Host;
use axum::http::Request;

#[tokio::main]
async fn main() {
    // ...
    let app = Router::new()
        .route(
            "/",
            any(|Host(hostname): Host, request: Request<Body>| async move {
                format!("Hi {hostname}")
            }),
        )
        .layer(Extension(state));
    // ...
}

相关问题