endstat/src/main.rs

104 lines
2.9 KiB
Rust

extern crate reqwest;
extern crate ron;
extern crate serde;
use reqwest::{Client, Url};
use ron::de::from_str;
use serde::Deserialize;
use std::error::Error;
use std::fs::read_to_string;
#[derive(Deserialize, Debug)]
struct EndpointConf {
label: Option<String>,
endpoint: Option<String>,
port: Option<u16>,
code: Option<u16>,
body: Option<String>,
}
#[derive(Deserialize, Debug)]
struct WebsiteConf {
label: String,
base: String,
endpoints: Vec<EndpointConf>,
}
#[derive(Deserialize, Debug)]
struct Config {
websites: Vec<WebsiteConf>,
}
#[derive(Debug)]
struct Status {
status: u8,
location: String,
domain: String,
endpoint: String,
error: Option<String>,
}
fn main() -> Result<(), Box<Error>> {
let client = Client::new();
let config = from_str::<Config>(&read_to_string("./endstat_conf.ron")?)?;
let mut results: Vec<Status> = vec![];
for website_conf in config.websites {
for endpoint in website_conf.endpoints {
let (label, path, port, code, body) = get_endpoint_info(endpoint);
let mut url = Url::parse(&website_conf.base)?.join(&path)?;
if let Err(e) = url.set_port(port) {
println!("{:?}", e);
}
let url = url.into_string();
let mut res = client.get(&url).send()?;
let does_code_match = res.status() == code;
let does_body_match = body.is_empty() || res.text()? == body;
results.push(if !does_code_match {
Status {
status: 1,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: Some(format!(
"Status code mismatch! {} != {}",
res.status().as_u16(),
code
)),
}
} else if !does_body_match {
Status {
status: 2,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: Some(format!("Body mismatch! {} != {}", res.text()?, body)),
}
} else {
Status {
status: 0,
location: url,
domain: website_conf.label.clone(),
endpoint: label,
error: None,
}
});
}
}
dbg!(results);
Ok(())
}
fn get_endpoint_info(endpoint: EndpointConf) -> (String, String, Option<u16>, u16, String) {
let path = endpoint.endpoint.unwrap_or_default();
let label = endpoint.label.unwrap_or_else(|| path.clone());
let code = endpoint.code.unwrap_or_else(|| 200);
let body = endpoint.body.unwrap_or_default();
(label, path, endpoint.port, code, body)
}