diff --git a/src/main.rs b/src/main.rs index feca341..a473a91 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use serde::{Deserialize, Serialize}; use std::{ error::Error, fs::read_to_string, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, MutexGuard}, time::{Duration, Instant}, }; @@ -60,53 +60,44 @@ struct FetchResults { type StatusState = Arc>; fn index(state: State) -> HttpResponse { - let mut state = state.lock().unwrap(); - let mut result = String::new(); - if Instant::now().duration_since(state.last_update) > Duration::from_secs(state.refresh_time) { - result = format!( - "it has been {:} seconds since last update, updating", - Instant::now().duration_since(state.last_update).as_secs() - ); - state.last_update = Instant::now(); - state.statuses = update_status(&state.config); - } - - let result = format!("{}\n{:?}", result, state.statuses); - HttpResponse::with_body(StatusCode::OK, result) + let state = update_state(state.lock().unwrap()); + HttpResponse::with_body(StatusCode::OK, "") } fn json_endpoint(state: State) -> WebResult>> { - let mut state = state.lock().unwrap(); + let state = update_state(state.lock().unwrap()); + Ok(Json(state.statuses.clone())) +} + +fn update_state(mut state: MutexGuard) -> MutexGuard { if Instant::now().duration_since(state.last_update) > Duration::from_secs(state.refresh_time) { state.last_update = Instant::now(); state.statuses = update_status(&state.config); } - Ok(Json(state.statuses.clone())) + state } fn main() -> Result<(), Box> { let config = from_str::(&read_to_string("./endstat_conf.ron")?)?; println!("running server"); - let sys = System::new("status"); - - let a: Arc> = Arc::from(Mutex::from(FetchResults { - last_update: Instant::now(), - refresh_time: config.refresh_time, - config: config.clone(), - statuses: update_status(&config), - })); server::new(move || { - App::with_state(a.clone()) + let state = Arc::from(Mutex::from(FetchResults { + last_update: Instant::now(), + refresh_time: config.refresh_time, + config: config.clone(), + statuses: update_status(&config), + })); + + App::with_state(state) .resource("/", |r| r.get().with(index)) .resource("/api", |r| r.get().with(json_endpoint)) }) .bind("0.0.0.0:8080")? - .start(); + .run(); - sys.run(); Ok(()) }