endstat/src/handlers.rs

77 lines
1.9 KiB
Rust
Raw Normal View History

2019-05-01 13:01:27 -07:00
use crate::{config::*, State};
2019-04-30 22:41:52 -07:00
use actix_web::{
error::ErrorInternalServerError, web::Data, Error as WebError, HttpResponse,
Result as WebResult,
};
2019-05-01 13:01:27 -07:00
use chrono::prelude::*;
2019-04-30 22:41:52 -07:00
use serde::Serialize;
use tera::{Context, Tera};
2019-05-01 09:58:10 -07:00
#[derive(Clone, Serialize, Default, Debug)]
2019-05-01 13:59:55 -07:00
pub struct EndpointStatus {
2019-05-01 11:13:46 -07:00
pub status: u8,
pub location: String,
pub endpoint: String,
pub error: Option<String>,
2019-04-30 22:41:52 -07:00
}
impl EndpointStatus {
pub fn ok(location: String, endpoint: String) -> Self {
EndpointStatus {
status: 0,
location,
endpoint,
error: None,
}
}
pub fn warn(location: String, endpoint: String, error: Option<String>) -> Self {
EndpointStatus {
status: 1,
location,
endpoint,
error,
}
}
pub fn error(location: String, endpoint: String, error: Option<String>) -> Self {
EndpointStatus {
status: 2,
location,
endpoint,
error,
}
}
}
2019-05-01 13:59:55 -07:00
#[derive(Serialize, Debug)]
pub struct StatusGroup {
pub label: String,
pub endpoints: Vec<EndpointStatus>,
}
2019-05-01 09:58:10 -07:00
#[derive(Serialize, Debug)]
2019-04-30 23:15:20 -07:00
pub struct QueryResults {
2019-05-01 13:15:18 -07:00
pub timestamp: DateTime<Utc>,
pub timestamp_str: String,
2019-04-30 22:41:52 -07:00
pub refresh_time: u64,
pub config: Config,
2019-05-01 13:59:55 -07:00
pub groups: Vec<StatusGroup>,
2019-04-30 22:41:52 -07:00
}
2019-04-30 23:15:20 -07:00
pub fn index(tmpl: Data<Tera>, state: Data<State>) -> WebResult<HttpResponse, WebError> {
2019-05-01 09:58:10 -07:00
let state = state.read().unwrap();
2019-04-30 22:41:52 -07:00
let mut ctx = Context::new();
ctx.insert("results", &*state);
let s = tmpl.render("index.html", &ctx).map_err(|e| {
println!("{:?}", e);
ErrorInternalServerError("Template error")
})?;
Ok(HttpResponse::Ok().content_type("text/html").body(s))
}
2019-04-30 23:15:20 -07:00
pub fn json_endpoint(state: Data<State>) -> HttpResponse {
2019-05-01 09:58:10 -07:00
let state = state.read().unwrap();
2019-05-01 13:59:55 -07:00
HttpResponse::Ok().json(&*state.groups)
2019-04-30 22:41:52 -07:00
}