Rouille - Handle HTML form - echo with POST

web Rouille POST post_input! Response html with_status_code

Part of the series about the Rouille micro-web framework in Rust.

Dependencies

examples/rouille/echo-post/Cargo.toml

[package]
name = "echo-post"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
rouille = "3.6"

The code

examples/rouille/echo-post/src/main.rs

#[macro_use]
extern crate rouille;

fn main() {
    let host = "localhost";
    let port = "8000";

    println!("Now listening on {host}:{port}");

    rouille::start_server(format!("{host}:{port}"), move |request| {
        router!(request,
            (GET) (/) => {
                rouille::Response::html(r#"
                    Good form
                    <form method="POST" action="/echo">
                    <input name="text">
                    <input type="submit" value="Echo">
                    </form>

                    <hr>
                    Form with extra hidden field.
                    <form method="POST" action="/echo">
                    <input name="text">
                    <input name="other" type="hidden" value="42">
                    <input type="submit" value="Echo">
                    </form>

                    <hr>
                    Form where the expected field is missing.
                    <form method="POST" action="/echo">
                    <input name="other">
                    <input type="submit" value="Echo">
                    </form>
                    "#)
            },
            (POST) (/echo) => {
                let req = post_input!(request, {
                    text: String,
                });

                match req {
                    Ok(data) => {
                        println!("Received data: {:?}", data);
                        rouille::Response::html(format!(r#"You typed in <b>{}</b> <a href="/">back</a>"#, data.text))
                    },
                    Err(post_error) => {
                        println!("Received error: {:?}", post_error);
                        rouille::Response::html(format!(r#"error <b>{}</b>  <a href="/">back</a>"#, post_error)).with_status_code(400)
                    },
                }
            },
            _ => rouille::Response::html("This page does <b>not</b> exist.").with_status_code(404)
        )
    });
}

Related Pages

Rouille a web micro-framework in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo