Skip to content

Commit 7a78ebe

Browse files
authored
Merge pull request #742 from joshtriplett/simple-state-example
Add simple state example
2 parents c63a652 + c8e2118 commit 7a78ebe

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

examples/state.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
use std::sync::atomic::{AtomicU32, Ordering};
2+
use std::sync::Arc;
3+
4+
#[derive(Clone)]
5+
struct State {
6+
value: Arc<AtomicU32>,
7+
}
8+
9+
impl State {
10+
fn new() -> Self {
11+
Self {
12+
value: Arc::new(AtomicU32::new(0)),
13+
}
14+
}
15+
}
16+
17+
#[async_std::main]
18+
async fn main() -> tide::Result<()> {
19+
tide::log::start();
20+
let mut app = tide::with_state(State::new());
21+
app.at("/").get(|req: tide::Request<State>| async move {
22+
let state = req.state();
23+
let value = state.value.load(Ordering::Relaxed);
24+
Ok(format!("{}\n", value))
25+
});
26+
app.at("/inc").get(|req: tide::Request<State>| async move {
27+
let state = req.state();
28+
let value = state.value.fetch_add(1, Ordering::Relaxed) + 1;
29+
Ok(format!("{}\n", value))
30+
});
31+
app.listen("127.0.0.1:8080").await?;
32+
Ok(())
33+
}

0 commit comments

Comments
 (0)