1

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")
        }
    }
}
Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
Dragury
  • 21
  • 4
  • it looks like [this](https://stackoverflow.com/questions/27791532/how-do-i-create-a-global-mutable-singleton) is more like what I think I'm looking for, but I found it through your link, so thanks for your response! – Dragury Jul 12 '19 at 15:12
  • TL;DR: use an `AtomicU64` and increment with [`fetch_add(1, ...)`](https://doc.rust-lang.org/std/sync/atomic/struct.AtomicU64.html#method.fetch_add) – Boiethios Jul 12 '19 at 15:12

1 Answers1

1

It looks like this is what I'm looking for as a safe way of accessing some kind of application state.

Dragury
  • 21
  • 4
  • Please, don't answer if this is a duplicate. You must rather mark your question as a duplicate of this one – Boiethios Jul 12 '19 at 15:14