Rocket - Return Status (arbitrary HTTP code)



examples/rocket/return-result/src/main.rs
#[macro_use]
extern crate rocket;

use rocket::http::Status;
use rocket::response::content;

#[get("/")]
fn index() -> content::RawHtml<&'static str> {
    content::RawHtml(r#"<a href="/language/rust">rust</a> <a href="/language/python">python</a>"#)
}

#[get("/language/<answer>")]
fn question(answer: &str) -> std::result::Result<content::RawHtml<&'static str>, Status> {
    if answer == "rust" {
        Ok(content::RawHtml("correct"))
    } else {
        Err(Status::BadRequest)
    }
}

#[catch(400)]
fn http_400() -> content::RawHtml<&'static str> {
    content::RawHtml("This is a 400 error")
}

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

#[cfg(test)]
mod tests;

examples/rocket/return-result/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_eq!(
        response.into_string(),
        Some(r#"<a href="/language/rust">rust</a> <a href="/language/python">python</a>"#.into())
    );
}

#[test]
fn language_rust() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/language/rust").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("correct".into()));
}

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

    assert_eq!(response.status(), Status::BadRequest);
    assert_eq!(
        response.headers().get_one("Content-Type").unwrap(),
        "text/html; charset=utf-8"
    );

    assert_eq!(response.into_string(), Some("This is a 400 error".into()));
}