clean up of main

This commit is contained in:
Edward Shen 2019-04-30 15:27:15 -04:00
parent 88e9c4df82
commit 38cad2e788
Signed by: edward
GPG key ID: F350507060ED6C90

View file

@ -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(())
}