basic/state.rs
1use std::sync::atomic::{AtomicUsize, Ordering};
2
3use afire::{Method, Response, Server};
4
5use crate::Example;
6
7// You can run this example with `cargo run --example basic -- state`
8
9// Create a structure to hold app state
10// The state is immutable, so you need to use an atomic type or a Interior Mutability type
11
12#[derive(Default)]
13struct App {
14 count: AtomicUsize,
15}
16
17pub struct State;
18
19impl Example for State {
20 fn name(&self) -> &'static str {
21 "state"
22 }
23
24 fn exec(&self) {
25 // Create a server on localhost port 8080 with a state of App
26 let mut server = Server::<App>::new("localhost", 8080).state(App::default());
27
28 // Add catch all route that takes in state and the request
29 server.stateful_route(Method::ANY, "**", |sta, _req| {
30 // Respond with and increment request count
31 Response::new().text(sta.count.fetch_add(1, Ordering::Relaxed))
32 });
33
34 // Start the server
35 // This will block the current thread
36 // Because there is a stateful route, this will panic if no state is set
37 server.start().unwrap();
38
39 // Now go to http://localhost:8080
40 // You should see the request count increment each time you refresh
41 }
42}