Extract constants and add config loader + example appsettings for niom-signaling; wire main to config

This commit is contained in:
ghost 2025-09-29 19:18:53 +02:00
parent 2021a4fab0
commit ffad23446a
5 changed files with 51 additions and 4 deletions

2
.gitignore vendored
View File

@ -19,4 +19,4 @@ target
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
.idea/

5
appsettings.example.json Normal file
View File

@ -0,0 +1,5 @@
{
"server": {
"bind": "127.0.0.1:3478"
}
}

24
src/config.rs Normal file
View File

@ -0,0 +1,24 @@
use serde::Deserialize;
use std::path::Path;
#[derive(Debug, Deserialize, Clone)]
pub struct ServerOptions {
pub bind: String,
}
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
pub server: ServerOptions,
}
impl Config {
pub fn from_file<P: AsRef<Path>>(p: P) -> Result<Self, Box<dyn std::error::Error>> {
let s = std::fs::read_to_string(p)?;
let cfg: Config = serde_json::from_str(&s)?;
Ok(cfg)
}
pub fn load_default() -> Result<Self, Box<dyn std::error::Error>> {
Self::from_file("appsettings.json")
}
}

3
src/constants.rs Normal file
View File

@ -0,0 +1,3 @@
// Central constants for niom-signaling
pub const DEFAULT_BIND: &str = "127.0.0.1:3478";
pub const DEFAULT_HOST_URL: &str = "http://localhost:3478";

View File

@ -3,6 +3,10 @@ use futures_util::StreamExt;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::broadcast;
mod constants;
mod config;
use crate::config::Config;
use crate::constants::*;
#[derive(Clone)]
struct AppState {
@ -25,15 +29,26 @@ async fn main() -> std::io::Result<()> {
let app_state = AppState {
broadcaster: Arc::new(tx)
};
// Try to load config, otherwise fall back to defaults
let cfg = match Config::load_default() {
Ok(c) => {
println!("Loaded config from appsettings.json");
c
}
Err(_) => {
println!("No config found, using defaults");
Config { server: crate::config::ServerOptions { bind: DEFAULT_BIND.to_string() } }
}
};
println!("Server is running on {}", DEFAULT_HOST_URL);
println!("Server is running on http://localhost:3478");
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(app_state.clone()))
.route("/ws", web::get().to(websocket_handler))
})
.bind("127.0.0.1:3478")?
.bind(&cfg.server.bind)?
.run()
.await
}