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");
}