clean up of main
This commit is contained in:
parent
88e9c4df82
commit
38cad2e788
1 changed files with 18 additions and 27 deletions
45
src/main.rs
45
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<Mutex<FetchResults>>;
|
||||
|
||||
fn index(state: State<StatusState>) -> 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<StatusState>) -> WebResult<Json<Vec<Status>>> {
|
||||
let mut state = state.lock().unwrap();
|
||||
let state = update_state(state.lock().unwrap());
|
||||
Ok(Json(state.statuses.clone()))
|
||||
}
|
||||
|
||||
fn update_state(mut state: MutexGuard<FetchResults>) -> MutexGuard<FetchResults> {
|
||||
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<Error>> {
|
||||
let config = from_str::<Config>(&read_to_string("./endstat_conf.ron")?)?;
|
||||
|
||||
println!("running server");
|
||||
let sys = System::new("status");
|
||||
|
||||
let a: Arc<Mutex<FetchResults>> = 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(())
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in a new issue