Rocket - echo GET

Rocket web GET

PArt of the Rocket series, expecting a single parameter as Query String.

examples/rocket/echo-get/Cargo.toml

[package]
name = "echo-get"
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/echo-get/src/main.rs

#[macro_use]
extern crate rocket;

use rocket_dyn_templates::{context, Template};

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

#[get("/echo?<text>")]
fn echo(text: String) -> Template {
    println!("text: {:?}", text);

    Template::render(
        "echo",
        context! {
            text: text
        },
    )
}

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

#[cfg(test)]
mod tests;

examples/rocket/echo-get/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>Echo</h1>"));
}

#[test]
fn echo_page() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client
        .get("/echo?text=Foo+Bar")
        .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 typed in <b>Foo Bar</b>".into())
    );
}

examples/rocket/echo-get/templates/echo.html.tera

You typed in <b>{{ text }}</b>

examples/rocket/echo-get/templates/index.html.tera

<h1>Echo</h1>
<form method="GET" action="/echo">
<input name="text">
<input type="submit" value="Echo">
</form>

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