Rocket - Hello World returning HTML

content::RawHtml Content-Type headers get_one

Part of the series about the Rocket web framework.

Dependencies

examples/rocket/hello-world-html/Cargo.toml

[package]
name = "hello-world-html"
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.0"

Code

examples/rocket/hello-world-html/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>")
}

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

#[cfg(test)]
mod tests;

The key is that the route function is defined to return content::RawHtml<&'static str> and then we call content::RawHtml to return the HTML.

This will set the Content-type to text/html.

Testing

We can verify it in our test using the response.headers().get_one("Content-Type") call and running

cargo test

examples/rocket/hello-world-html/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/html; charset=utf-8"
    );
    assert_eq!(response.into_string(), Some("Hello, <b>world!</b>".into()));
}

Running

We can also launch the web service using

cargo run

And verify the output in our browser or by using curl in a separate terminal:

$ curl -i http://localhost:8000

HTTP/1.1 200 OK
content-type: text/html; charset=utf-8
server: Rocket
permissions-policy: interest-cohort=()
x-content-type-options: nosniff
x-frame-options: SAMEORIGIN
content-length: 20
date: Tue, 02 Jan 2024 14:11:04 GMT

Hello, <b>world!</b>

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