use axum::{extract::Query, routing::get, Json, Router};
use monocoque_core::BtrfsSpace;
use serde::{Deserialize, Serialize};
use std::net::SocketAddr;
#[derive(Deserialize)]
struct SpaceQuery {
unit: Option<String>,
}
#[derive(Serialize)]
struct ConvertedSpace {
total: f64,
used: f64,
free: f64,
unit: String,
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/api/space", get(get_space));
let addr = SocketAddr::from(([0, 0, 0, 0], 4001));
println!("Listening on http://{addr}");
axum::serve(tokio::net::TcpListener::bind(addr).await.unwrap(), app)
.await
.unwrap();
}
async fn get_space(Query(params): Query<SpaceQuery>) -> Json<serde_json::Value> {
let space = monocoque_core::get_space("/srv/").unwrap();
match params.unit.as_deref() {
None => Json(serde_json::to_value(space).unwrap()),
Some(unit) => {
let divisor: f64 = match unit.to_lowercase().as_str() {
"kb" => 1024.0,
"mb" => 1024.0_f64.powi(2),
"gb" => 1024.0_f64.powi(3),
"tb" => 1024.0_f64.powi(4),
"b" => 1.0,
_ => 1.0,
};
let converted = ConvertedSpace {
total: space.total_bytes as f64 / divisor,
used: space.used_bytes as f64 / divisor,
free: space.free_bytes as f64 / divisor,
unit: unit.to_lowercase(),
};
Json(serde_json::to_value(converted).unwrap())
}
}
}