[][src]Macro vial::use_state

macro_rules! use_state {
    ($state:expr) => { ... };
}

Gives Vial a state object to manage globally. You can access it by calling request.state::<YourStruct>() in an action.

The vial::use_state!() macro should be called immediately before calling vial::run!() in your application.

It expects one argument: a Send + Sync + 'static object you want to share between all requests.

use std::sync::atomic::{AtomicUsize, Ordering};
use vial::prelude::*;

routes! {
    GET "/" => hello;
    GET "/count" => count;
}

fn hello(req: Request) -> impl Responder {
    req.state::<HitCount>().0.fetch_add(1, Ordering::Relaxed);
    format!("Hits: {}", count(req))
}

fn count(req: Request) -> String {
    req.state::<HitCount>()
        .0
        .load(Ordering::Relaxed)
        .to_string()
}

#[derive(Default)]
struct HitCount(AtomicUsize);

fn main() {
    use_state!(HitCount::default());
    run!().unwrap();
}