Skip to content
Myr

main.rs

This file

Path

examples/form/src/main.rs

125 lines · 3.3 KiB · Rust

Last changed by

examples: remove redundant borrows in form example format args (#3781)Justinbefore adoption4a72e06

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-form5//! ```67use axum::{extract::Form, response::Html, routing::get, Router};8use serde::Deserialize;9use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};1011#[tokio::main]12async fn main() {13    tracing_subscriber::registry()14        .with(15            tracing_subscriber::EnvFilter::try_from_default_env()16                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),17        )18        .with(tracing_subscriber::fmt::layer())19        .init();2021    // build our application with some routes22    let app = app();2324    // run it25    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")26        .await27        .unwrap();28    tracing::debug!("listening on {}", listener.local_addr().unwrap());29    axum::serve(listener, app).await;30}3132fn app() -> Router {33    Router::new().route("/", get(show_form).post(accept_form))34}3536async fn show_form() -> Html<&'static str> {37    Html(38        r#"39        <!doctype html>40        <html>41            <head></head>42            <body>43                <form action="/" method="post">44                    <label for="name">45                        Enter your name:46                        <input type="text" name="name">47                    </label>4849                    <label>50                        Enter your email:51                        <input type="text" name="email">52                    </label>5354                    <input type="submit" value="Subscribe!">55                </form>56            </body>57        </html>58        "#,59    )60}6162#[derive(Deserialize, Debug)]63#[allow(dead_code)]64struct Input {65    name: String,66    email: String,67}6869async fn accept_form(Form(input): Form<Input>) -> Html<String> {70    dbg!(&input);71    Html(format!("email='{}'\nname='{}'\n", input.email, input.name))72}7374#[cfg(test)]75mod tests {76    use super::*;77    use axum::{78        body::Body,79        http::{self, Request, StatusCode},80    };81    use http_body_util::BodyExt;82    use tower::ServiceExt; // for `call`, `oneshot`, and `ready` // for `collect`8384    #[tokio::test]85    async fn test_get() {86        let app = app();8788        let response = app89            .oneshot(Request::get("/").body(Body::empty()).unwrap())90            .await91            .unwrap();9293        assert_eq!(response.status(), StatusCode::OK);9495        let body = response.into_body().collect().await.unwrap().to_bytes();96        let body = std::str::from_utf8(&body).unwrap();9798        assert!(body.contains(r#"<input type="submit" value="Subscribe!">"#));99    }100101    #[tokio::test]102    async fn test_post() {103        let app = app();104105        let response = app106            .oneshot(107                Request::post("/")108                    .header(109                        http::header::CONTENT_TYPE,110                        mime::APPLICATION_WWW_FORM_URLENCODED.as_ref(),111                    )112                    .body(Body::from("name=foo&email=bar@axum"))113                    .unwrap(),114            )115            .await116            .unwrap();117118        assert_eq!(response.status(), StatusCode::OK);119120        let body = response.into_body().collect().await.unwrap().to_bytes();121        let body = std::str::from_utf8(&body).unwrap();122123        assert_eq!(body, "email='bar@axum'\nname='foo'\n");124    }125}