Rocket - Redirect with parameters



examples/rocket/redirect-with-parameters/src/main.rs
#[macro_use]
extern crate rocket;

use rocket::response::Redirect;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[get("/user/<id>?<msg>")]
fn user(id: u32, msg: &str) -> String {
    format!("id: {id} msg: {msg}")
}

#[get("/group/<id>?<msg>")]
fn group(id: u32, msg: Option<&str>) -> String {
    format!("id: {id} msg: {msg:?}")
}

#[get("/other")]
fn other() -> Redirect {
    Redirect::to(uri!(user(23, "hello")))
}

#[get("/redir-value")]
fn redir_value() -> Redirect {
    Redirect::to(uri!(group(42, Some("message"))))
}

#[get("/redir-none")]
fn redir_none() -> Redirect {
    // type annotations needed for `std::option::Option<_>`
    //Redirect::to(uri!(group(42, None)))

    let msg: Option<&str> = None;
    Redirect::to(uri!(group(42, msg)))
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount(
        "/",
        routes![index, user, other, group, redir_value, redir_none],
    )
}

#[cfg(test)]
mod tests;

examples/rocket/redirect-with-parameters/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()));

    let response = client.get("/other").dispatch();
    assert_eq!(response.status(), Status::SeeOther);
    assert_eq!(
        response.headers().get_one("Location").unwrap(),
        "/user/23?msg=hello"
    );
    assert_eq!(response.into_string(), None);

    let response = client.get("/redir-value").dispatch();
    assert_eq!(response.status(), Status::SeeOther);
    assert_eq!(
        response.headers().get_one("Location").unwrap(),
        "/group/42?msg=message"
    );
    assert_eq!(response.into_string(), None);

    let response = client.get("/redir-none").dispatch();
    assert_eq!(response.status(), Status::SeeOther);
    assert_eq!(response.headers().get_one("Location").unwrap(), "/group/42");
    assert_eq!(response.into_string(), None);
}