Files
axum/examples/form/src/main.rs
T

131 lines
3.4 KiB
Rust
Raw Normal View History

2021-08-02 23:09:09 +02:00
//! Run with
//!
//! ```not_rust
//! cargo run -p example-form
2021-08-02 23:09:09 +02:00
//! ```
use axum::{extract::Form, response::Html, routing::get, Router};
2021-06-13 11:01:40 +02:00
use serde::Deserialize;
2022-03-06 12:37:00 +01:00
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
2021-06-13 11:01:40 +02:00
#[tokio::main]
async fn main() {
2022-03-06 12:37:00 +01:00
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
)
2022-03-06 12:37:00 +01:00
.with(tracing_subscriber::fmt::layer())
.init();
2021-06-13 11:01:40 +02:00
// build our application with some routes
2025-03-17 14:31:17 +02:00
let app = app();
2021-06-13 11:01:40 +02:00
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
2021-06-19 12:50:33 +02:00
.await
.unwrap();
tracing::debug!("listening on {}", listener.local_addr().unwrap());
2025-12-28 09:25:50 +01:00
axum::serve(listener, app).await;
2021-06-13 11:01:40 +02:00
}
2025-03-17 14:31:17 +02:00
fn app() -> Router {
Router::new().route("/", get(show_form).post(accept_form))
}
2021-08-18 00:04:15 +02:00
async fn show_form() -> Html<&'static str> {
Html(
2021-06-13 11:01:40 +02:00
r#"
<!doctype html>
<html>
<head></head>
<body>
<form action="/" method="post">
<label for="name">
Enter your name:
<input type="text" name="name">
</label>
<label>
Enter your email:
<input type="text" name="email">
</label>
<input type="submit" value="Subscribe!">
</form>
</body>
</html>
"#,
)
}
#[derive(Deserialize, Debug)]
2021-10-07 16:49:57 +02:00
#[allow(dead_code)]
2021-06-13 11:01:40 +02:00
struct Input {
name: String,
email: String,
}
2025-03-17 14:31:17 +02:00
async fn accept_form(Form(input): Form<Input>) -> Html<String> {
2021-06-13 11:01:40 +02:00
dbg!(&input);
2025-03-17 14:31:17 +02:00
Html(format!(
"email='{}'\nname='{}'\n",
&input.email, &input.name
))
}
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{self, Request, StatusCode},
};
use http_body_util::BodyExt;
use tower::ServiceExt; // for `call`, `oneshot`, and `ready` // for `collect`
#[tokio::test]
async fn test_get() {
let app = app();
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body = std::str::from_utf8(&body).unwrap();
assert!(body.contains(r#"<input type="submit" value="Subscribe!">"#));
}
#[tokio::test]
async fn test_post() {
let app = app();
let response = app
.oneshot(
Request::builder()
.method(http::Method::POST)
.uri("/")
.header(
http::header::CONTENT_TYPE,
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),
)
.body(Body::from("name=foo&email=bar@axum"))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
let body = std::str::from_utf8(&body).unwrap();
assert_eq!(body, "email='bar@axum'\nname='foo'\n");
}
2021-06-13 11:01:40 +02:00
}