Get A URL Query Parameter From A Request In axum
Code
[package]
name = "axum_query_param_test"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
axum = "0.6"
Code
use axum::extract::Query;
use axum::response::IntoResponse;
use axum::routing::get;
use axum::{response::Html, Router};
use serde::Deserialize;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let welcome_route = Router::new().route("/welcome", get(welcome_query_handler));
let addr = SocketAddr::from(([127, 0, 0, 1], 8181));
axum::Server::bind(&addr)
.serve(welcome_route.into_make_service())
.await
.unwrap();
}
#[derive(Debug, Deserialize)]
struct WelcomeParams {
name: Option<String>,
}
async fn welcome_query_handler(Query(params): Query<WelcomeParams>) -> impl IntoResponse {
println!("Got request for /welcome");
match params.name {
Some(name) => Html(format!("Hello, {}", name.as_str())),
None => Html("Hello, whoever you are".to_string()),
}
}
Reference
Rust Axum Full Course
Jeremy Chone
This is the video I got the base example off of. It did some fancier stuff that I removed to simplify it to make it easier for me to understand.