Rocket: Request guard numbers

Rocket

examples/rocket/request-guard-numbers/Cargo.toml

[package]
name = "request-guard-numbers"
version = "0.1.0"
edition = "2021"

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

[dependencies]
rocket = "0.5.0"

examples/rocket/request-guard-numbers/src/main.rs

#[macro_use]
extern crate rocket;

use rocket::response::content;

struct Guess {
    guess: 
}

#[get("/")]
fn index() -> content::RawHtml<&'static str> {
    content::RawHtml(r#"
    <form action="/check">
    <input name="guess">
    <input type="submit" value="Try">
    "#)
}

#[get("/check?<guess>")]
fn check(guess: u32) -> content::RawHtml<String> {
    content::RawHtml(format!("The guess was: {guess}"))
}

#[catch(422)]
fn not_processed() -> content::RawHtml<&'static str> {
    content::RawHtml("This is a 422 errror")
}


#[launch]
fn rocket() -> _ {
    rocket::build()
    .mount("/", routes![index, check])
    .register("/", catchers![not_processed])
}

#[cfg(test)]
mod tests;


examples/rocket/request-guard-numbers/src/tests.rs

use rocket::http::Status;
use rocket::local::blocking::Client;

#[test]
fn hello_world() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/").dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.headers().get_one("Content-Type").unwrap(),
        "text/plain; charset=utf-8"
    );
    assert_eq!(response.into_string(), Some("Hello, world!".into()));
}


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