I'm exploring using nickel-rs for a web app, and as such I'm currently writing some basic programs that replicate behaviour that I've been able to implement with python and flask. For this specific case I wanted to track the number of requests that have come in for a specific route. In python this is easy with a global variable, and I assume the Global Interpreter Lock provides some guarantee that the variable will only be accessed by one thing at a time(not that this is a huge issue for this specific scenario). In Rust however, to do the same thing I've had to use unsafe
whenever I access my counter, which seems to suggest that there could be a safe way of implementing application state?
I've tried using Nickel::with_data(config)
where config is a struct with a single u64 in it, and by using the server_data() method of the Request implementation I can get the value of my counter, but any changes I manage to write to the struct by borrowing the server_data() struct result as mutable, but the new value didn't persist between method calls.
I tried to adapt to what is happening here.
So far the only method that I've managed to get working is the code included with this post.
#[macro_use]
extern crate nickel;
use nickel::{Nickel, HttpRouter};
static mut REQUEST_COUNT: u64 = 0;
fn main() {
let mut nickel_app = Nickel::new();
nickel_app.get("/", middleware! {
unsafe {
println!("REQUEST_COUNT: {} -> {}", REQUEST_COUNT, REQUEST_COUNT + 1u64);
REQUEST_COUNT += 1u64;
}
"index"
});
nickel_app.get("/req", middleware! {
unsafe {
format!("REQUEST_COUNT is {}", REQUEST_COUNT)
}
});
match nickel_app.listen("127.0.0.1:8080") {
Ok(_) => {}
Err(_) => {
panic!("Couldn't bind to 127.0.0.1:8080")
}
}
}