1
Fork 0
mirror of https://github.com/redstrate/Kawari.git synced 2025-04-25 00:17:45 +00:00

Fix the admin server not creating config.json if not found

This commit is contained in:
Joshua Goins 2024-05-11 13:13:03 -04:00
parent fa6c2ddf7f
commit 0918700a85
3 changed files with 30 additions and 19 deletions

1
.gitignore vendored
View file

@ -1,2 +1,3 @@
/target
.idea/
config.json

View file

@ -10,6 +10,14 @@ use axum::response::{Html, Redirect};
use axum::routing::post;
use kawari::config::Config;
fn get_config() -> Config {
if let Ok(data) = std::fs::read_to_string("config.json") {
serde_json::from_str(&data).expect("Failed to parse")
} else {
Config::default()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
struct GateStatus {
status: i32,
@ -18,14 +26,9 @@ struct GateStatus {
async fn root() -> Html<String> {
tracing::info!("Requesting gate status...");
// read config
if let Ok(data) = std::fs::read_to_string("config.json") {
let config: Config = serde_json::from_str(&data).expect("Failed to parse");
let config = get_config();
Html(format!("<p>Gate open:{}</p><form action='apply' method='post'><input type='checkbox' id='gate_open' name='gate_open' checked /><button type='submit'>Apply</button></form>", config.gate_open))
} else {
Html(format!("unknown error"))
}
Html(format!("<p>Gate open:{}</p><form action='apply' method='post'><input type='checkbox' id='gate_open' name='gate_open' checked /><button type='submit'>Apply</button></form>", config.gate_open))
}
#[derive(Deserialize, Debug)]
@ -37,21 +40,20 @@ struct Input {
async fn apply(Form(input): Form<Input>) -> Redirect {
tracing::info!("Apply config changes...");
if let Ok(data) = std::fs::read_to_string("config.json") {
let mut config: Config = serde_json::from_str(&data).expect("Failed to parse");
if let Some(gate_open) = input.gate_open {
config.gate_open = gate_open == "on";
} else {
config.gate_open = false;
}
let mut config = get_config();
serde_json::to_writer(
&std::fs::File::create("config.json").unwrap(),
&config,
)
.expect("TODO: panic message");
if let Some(gate_open) = input.gate_open {
config.gate_open = gate_open == "on";
} else {
config.gate_open = false;
}
serde_json::to_writer(
&std::fs::File::create("config.json").unwrap(),
&config,
)
.expect("TODO: panic message");
Redirect::to("/")
}

View file

@ -3,4 +3,12 @@ use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
pub struct Config {
pub gate_open: bool
}
impl Default for Config {
fn default() -> Self {
Self {
gate_open: false,
}
}
}