Rocket - 404 page with static content



examples/rocket/http-404-page-with-static-content/src/main.rs
#[macro_use]
extern crate rocket;

use rocket::response::content;

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

#[catch(404)]
fn not_found() -> content::RawHtml<&'static str> {
    const BODY: &str = include_str!("templates/404.html");
    content::RawHtml(BODY)
}

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

#[cfg(test)]
mod tests;

examples/rocket/http-404-page-with-static-content/src/templates/404.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
  <link href="/css/skeleton.css" rel="stylesheet">
  <script src="/js/skeleton.js"></script>
 
  <title>404 Page not found</title>
</head>
<body>
<h1>Ooups</h1>
This page was not found.
 
</body>
</html>

examples/rocket/http-404-page-with-static-content/src/tests.rs
use rocket::form::validate::Contains;
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("Hello, <b>world!</b>".into()));
}

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

    assert_eq!(response.status(), Status::NotFound);
    assert_eq!(
        response.headers().get_one("Content-Type").unwrap(),
        "text/html; charset=utf-8"
    );
    let html = response.into_string().unwrap();
    assert!(html.contains("<title>404 Page not found</title>"));
    assert!(html.contains("<h1>Ooups</h1>"));
}