Rust Rocket: In memory hit counter using state

Rocket AtomicUsize Ordering State manage

Based on the managed state example.

Dependencies

examples/rocket/in-memory-hit-counter-state/Cargo.toml

[package]
name = "rocket-sessions"
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/in-memory-hit-counter-state/src/main.rs

#[macro_use]
extern crate rocket;

use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;

use rocket::response::content;
use rocket::State;

struct HitCount {
    count: AtomicUsize
}

#[get("/")]
fn index(hit_count: &State<HitCount>) -> content::RawHtml<String> {
    //let current_count = hit_count.count.load(Ordering::Relaxed);
    let current_count = hit_count.count.fetch_add(1, Ordering::Relaxed);

    content::RawHtml(format!("Rocket Counter: {current_count}"))
}

#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![index])
        .manage(HitCount { count: AtomicUsize::new(0) })
}

#[cfg(test)]
mod tests;


Test

examples/rocket/in-memory-hit-counter-state/src/tests.rs

use rocket::http::Status;
use rocket::local::blocking::Client;

#[test]
fn counter() {
    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().unwrap(), "Rocket Counter: 0");


    let response = client.get("/").dispatch();
    assert_eq!(response.into_string().unwrap(), "Rocket Counter: 1");

    let response = client.get("/").dispatch();
    assert_eq!(response.into_string().unwrap(), "Rocket Counter: 2");
}

#[test]
fn _another_counter() {
    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().unwrap(), "Rocket Counter: 0");


    let response = client.get("/").dispatch();
    assert_eq!(response.into_string().unwrap(), "Rocket Counter: 1");
}

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