Add client module for getting data from SpaceAPI endpoint
This commit is contained in:
parent
f75c178f8f
commit
5452a7e06f
3 changed files with 42 additions and 0 deletions
|
@ -5,3 +5,7 @@ edition = "2021"
|
|||
|
||||
[dependencies]
|
||||
clap = { version = "4.2.7", features = ["cargo", "derive"] }
|
||||
regex = "1.8.1"
|
||||
reqwest = { version = "0.11.17", features = ["blocking", "json"] }
|
||||
serde_json = "1.0.96"
|
||||
spaceapi = "0.9.0"
|
||||
|
|
36
src/client.rs
Normal file
36
src/client.rs
Normal file
|
@ -0,0 +1,36 @@
|
|||
use regex::Regex;
|
||||
use spaceapi::Status;
|
||||
|
||||
fn get_spaceapi(url: String) -> Status {
|
||||
let user_agent = "spaceapi2prometheus";
|
||||
let status: Status;
|
||||
loop {
|
||||
let client = reqwest::blocking::Client::builder()
|
||||
.user_agent(user_agent)
|
||||
.build();
|
||||
if let Ok(c) = client {
|
||||
let res = c.get(url).send().unwrap().text().unwrap();
|
||||
status = serde_json::from_str(&res).unwrap();
|
||||
break;
|
||||
}
|
||||
eprintln!("Failed to connect to endpoint, trying again!");
|
||||
std::thread::sleep(std::time::Duration::from_millis(10 * 1000));
|
||||
}
|
||||
|
||||
status
|
||||
}
|
||||
|
||||
fn parse_capacity(msg: &str) -> i8 {
|
||||
let regex = Regex::new(r"\d*").unwrap();
|
||||
let captures = regex.captures(msg).unwrap();
|
||||
|
||||
captures[0].parse::<i8>().unwrap()
|
||||
}
|
||||
|
||||
pub fn get_prometheus_string(url: String) -> String {
|
||||
let status = get_spaceapi(url);
|
||||
let capacity = parse_capacity(&status.clone().state.unwrap().message.unwrap());
|
||||
let lastchange = status.state.unwrap().lastchange.unwrap();
|
||||
|
||||
format!("people {} {}000\n", capacity, lastchange)
|
||||
}
|
|
@ -1,5 +1,7 @@
|
|||
use clap::Parser;
|
||||
|
||||
mod client;
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(version, about)]
|
||||
struct Cli {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue