Rouille - Hello World in text/html

web Rouille start_server router! GET html 404 Not Found with_status_code

Part of the series about the Rouille micro-web framework in Rust.

Dependency

examples/rouille/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]
rouille = "3.6"

The code

examples/rouille/hello-world-html/src/main.rs

#[macro_use]
extern crate rouille;

fn main() {
    let host = "localhost";
    let port = "8000";

    println!("Now listening on {host}:{port}");

    rouille::start_server(format!("{host}:{port}"), move |request| {
        router!(request,
            (GET) (/) => {
                rouille::Response::html("Hello <b>world!</b>")
            },
            _ => rouille::Response::html("This page does <b>not</b> exist.").with_status_code(404)
        )
    });
}

Running the web application

$ curl -i http://localhost:8000/

The response is:

HTTP/1.1 200 OK
Server: tiny-http (Rust)
Date: Mon, 01 Jan 2024 13:00:06 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 19

Hello <b>world!</b>

Here we can see the Content-Type being text/html.

If we visit the URL http://localhost:8000/ we'll see the word world! in bold.

404 Not Found

This time, instead of using the empty_404 call we used the html call and changed the status code manually to be 404.

_ => rouille::Response::html("This page does <b>not</b> exist.").with_status_code(404)

If we visit any page other than the root page we'll see the special message "This page does not exist." and the word not is being bold.

We can use curl to verify it:

$ curl -i http://localhost:8000/qqrq
HTTP/1.1 404 Not Found
Server: tiny-http (Rust)
Date: Mon, 01 Jan 2024 13:07:17 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 32

This page does <b>not</b> exist.

Related Pages

Rouille a web micro-framework in 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