Trying to get the full request URI (scheme + authority + path)
I have found the discussion: https://github.com/tokio-rs/axum/discussions/1149 which says that Request.uri() should have it. So I tried the following:
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();
}
And run curl -v "http://localhost:8080/test"
but I get:
The request is: /test
thread 'tokio-runtime-worker' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:59
It seems like it only contains the path.
I also found the other discussion: https://github.com/tokio-rs/axum/discussions/858
which suggests that axum::http::Uri
should be able to extract all the details, but I get the same issue:
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"] }
http://127.0.0.1/test
. How can I get axum to give me the full request URL, which is expected to behttp://127.0.0.1/test
. Using bothRequest.uri()
andaxum::http::Uri
only gives me the path/test
and nothttp://127.0.0.1/test
. Axum should be able to give me the full request URI, right? I don't want to hardcode the valueshttp
,127.0.0.1
, and8080
to reconstruct the whole URL. It makes it less flexible. I briefly used actix-web and I was able to get the full request URL – Unfetter