1
0
mirror of https://github.com/actix/actix-website synced 2025-02-08 22:36:07 +01:00

56 lines
1.2 KiB
Rust
Raw Normal View History

2019-06-15 16:37:08 -04:00
// <arc>
2020-09-12 16:21:54 +01:00
use actix_web::{get, web, App, HttpServer, Responder};
2022-04-07 16:22:17 +01:00
use std::{
cell::Cell,
sync::atomic::{AtomicUsize, Ordering},
sync::Arc,
};
2019-06-15 16:37:08 -04:00
2019-06-20 04:20:12 -04:00
#[derive(Clone)]
struct AppState {
local_count: Cell<usize>,
global_count: Arc<AtomicUsize>,
2019-06-20 04:20:12 -04:00
}
2020-09-12 16:21:54 +01:00
#[get("/")]
2019-12-29 02:08:25 +09:00
async fn show_count(data: web::Data<AppState>) -> impl Responder {
format!(
"global_count: {}\nlocal_count: {}",
data.global_count.load(Ordering::Relaxed),
data.local_count.get()
)
2019-06-20 04:20:12 -04:00
}
2019-06-15 16:37:08 -04:00
2020-09-12 16:21:54 +01:00
#[get("/add")]
2019-12-29 02:08:25 +09:00
async fn add_one(data: web::Data<AppState>) -> impl Responder {
data.global_count.fetch_add(1, Ordering::Relaxed);
2019-06-15 16:37:08 -04:00
let local_count = data.local_count.get();
data.local_count.set(local_count + 1);
format!(
"global_count: {}\nlocal_count: {}",
data.global_count.load(Ordering::Relaxed),
data.local_count.get()
)
2019-06-15 16:37:08 -04:00
}
2020-09-12 16:21:54 +01:00
#[actix_web::main]
2019-12-29 02:08:25 +09:00
async fn main() -> std::io::Result<()> {
2019-06-20 04:20:12 -04:00
let data = AppState {
local_count: Cell::new(0),
global_count: Arc::new(AtomicUsize::new(0)),
2019-06-20 04:20:12 -04:00
};
2019-06-15 16:37:08 -04:00
2019-06-20 04:20:12 -04:00
HttpServer::new(move || {
App::new()
2022-02-26 03:56:24 +00:00
.app_data(web::Data::new(data.clone()))
2020-09-12 16:21:54 +01:00
.service(show_count)
.service(add_one)
2019-06-15 16:37:08 -04:00
})
2022-02-26 03:56:24 +00:00
.bind(("127.0.0.1", 8080))?
2019-06-20 04:20:12 -04:00
.run()
2019-12-29 02:08:25 +09:00
.await
2019-06-15 16:37:08 -04:00
}
// </arc>