Get A URL Path Based Parameter From A Request In axum
Code
[package]
name = "axum_dev_watch"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
axum = "0.6"
Code
use axum::extract::Path;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{response::Html, Router};
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let routes_all = Router::new().merge(welcome_route());
let addr = SocketAddr::from(([127, 0, 0, 1], 8181));
axum::Server::bind(&addr)
.serve(routes_all.into_make_service())
.await
.unwrap();
}
fn welcome_route() -> Router {
Router::new().route("/welcome/:name", get(welcome_path_handler))
}
async fn welcome_path_handler(Path(name): Path<String>) -> impl IntoResponse {
println!("Got request for /welcome");
Html(format!("Hello, {}", name))
}
Notes
-
I'm splitting the route into its own function and using `.merge()`` on it. It's rare I end up with a single route and this preps for that