Rocket - process Query String of a GET request

Rocket web GET

Part of the Rocket series.

examples/rocket/query-string/Cargo.toml

[package]
name = "query-string"
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"
rocket_dyn_templates = { version = "0.1", features = ["tera"] }

examples/rocket/query-string/src/main.rs

#[macro_use]
extern crate rocket;

use rocket_dyn_templates::{context, Template};


#[get("/")]
fn index() -> Template {
    Template::render("index", context! {})
}

#[get("/show?<shape>&<color>")]
fn show(shape: String, color: String) -> Template {
    println!("shape: {} {}", shape, color);

    Template::render(
        "show",
        context! {
            shape: shape,
            color: color
        },
    )
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index, show])
        .attach(Template::fairing())
}

#[cfg(test)]
mod tests;

examples/rocket/query-string/src/tests.rs

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

#[test]
fn main_page() {
    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/html; charset=utf-8"
    );
    assert!(response.into_string().unwrap().contains("<h1>Show</h1>"));
}

#[test]
fn show_page() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client
        .get("/show?color=blue&shape=circle")
        .dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(
        response.headers().get_one("Content-Type").unwrap(),
        "text/html; charset=utf-8"
    );
    assert_eq!(
        response.into_string(),
        Some("You selected <b>circle</b> and <b>blue</b>".into())
    );
}

examples/rocket/query-string/templates/index.html.tera

<h1>Show</h1>
<form method="GET" action="/show">
<input name="shape" type="radio" value="square"> square
<input name="shape" type="radio" value="circle"> circle
<input name="shape" type="radio" value="triangle"> triangle
<input name="color" type="text">
<input type="submit" value="Show">
</form>

examples/rocket/query-string/templates/show.html.tera

You selected <b>{{ shape }}</b> and <b>{{ color }}</b>

TODO

  • Add more data types to the form and how we handle it
  • Add checkbox with multiple values.

Related Pages

Rocket - web development with 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