From 38e8b6e8ccf864312c74eac39b17378e584f7cb0 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sun, 8 Dec 2024 20:42:26 +0700 Subject: [PATCH] Create web_dashboard.rs --- src/dashboard/web_dashboard.rs | 41 ++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/dashboard/web_dashboard.rs diff --git a/src/dashboard/web_dashboard.rs b/src/dashboard/web_dashboard.rs new file mode 100644 index 0000000..e1fb7b9 --- /dev/null +++ b/src/dashboard/web_dashboard.rs @@ -0,0 +1,41 @@ +use actix_web::{web, App, HttpServer, HttpResponse, Responder, middleware}; +use serde_json::json; +use std::sync::Mutex; + +#[derive(Clone)] +struct AppState { + user_count: Mutex, +} + +async fn index(data: web::Data) -> impl Responder { + let count = data.user_count.lock().unwrap(); + HttpResponse::Ok().json(json!({ + "message": "Welcome to the Dashboard!", + "user_count": *count, + })) +} + +async fn increment_user_count(data: web::Data) -> impl Responder { + let mut count = data.user_count.lock().unwrap(); + *count += 1; + HttpResponse::Ok().json(json!({ + "user_count": *count, + })) +} + +pub async fn run_web_dashboard() -> std::io::Result<()> { + let state = AppState { + user_count: Mutex::new(0), + }; + + HttpServer::new(move || { + App::new() + .data(state.clone()) + .wrap(middleware::Logger::default()) + .route("/", web::get().to(index)) + .route("/increment", web::post().to(increment_user_count)) + }) + .bind("127.0.0.1:8080")? + .run() + .await +}