Get POST Values From HTML Form Input In axum
[package]
name = "axum_post_process"
version = "0.1.0"
edition = "2021"
[dependencies]
tokio = { version = "1", features = ["full"] }
axum = { version = "0.6", features = ["form"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1.0.105"
use axum::extract::Form;
use axum::response::IntoResponse;
use axum::response::Redirect;
use axum::routing::get;
use axum::routing::post;
use axum::{response::Html, Router};
use serde::Deserialize;
use std::net::SocketAddr;
#[tokio::main]
async fn main() {
let routes = Router::new()
.route("/", post(post_handler).get(get_handler))
.route("/success", get(get_success_handler));
let addr = SocketAddr::from(([127, 0, 0, 1], 8484));
axum::Server::bind(&addr)
.serve(routes.into_make_service())
.await
.unwrap();
}
#[derive(Deserialize, Debug)]
struct FormData {
alfa: String,
}
async fn post_handler(Form(request): Form<FormData>) -> impl IntoResponse {
println!("Got: {}", request.alfa);
Redirect::to("/success")
}
async fn get_handler() -> impl IntoResponse {
println!("Got GET at /");
Html(format!(
r#"
<form action="/" method="post">
<input type="hidden" name="alfa" value="bravo"/>
<input type="submit"/>
</form>"#
))
}
async fn get_success_handler() -> impl IntoResponse {
println!("Got GET at /success");
Html(format!(r#"<div>success!</div>"#))
}
~ fin ~