From 167772b87698cce479090dbe5bd3d1cc7c1bc808 Mon Sep 17 00:00:00 2001 From: xengineering Date: Sat, 20 Dec 2025 14:20:42 +0100 Subject: Implement passing user configuration This allows overwriting values of the default configuration with custom ones. --- config.go | 26 +++++++++++++++++++++++++- flags.go | 15 +++++++++++++++ main.go | 5 ++++- meson.build | 1 + 4 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 flags.go diff --git a/config.go b/config.go index 7d3cab8..dfea550 100644 --- a/config.go +++ b/config.go @@ -7,6 +7,7 @@ import ( "log" "net" "net/url" + "os" "regexp" "strconv" "time" @@ -120,7 +121,21 @@ func (sc *StartupConfig) FromJSON(data []byte) error { return nil } -func GetStartupConfig() StartupConfig { +func (sc *StartupConfig) FromFile(path string) error { + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("Failed to read config file '%s': %w", path, err) + } + + err = sc.FromJSON(data) + if err != nil { + return fmt.Errorf("Could not parse config file '%s': %w", path, err) + } + + return nil +} + +func GetStartupConfig(path string) StartupConfig { config := StartupConfig{} err := config.FromJSON(defaultConfig) @@ -128,5 +143,14 @@ func GetStartupConfig() StartupConfig { log.Fatalf("Could not parse default config: %v", err) } + if path != "" { + log.Printf("Config path: %s", path) + + err = config.FromFile(path) + if err != nil { + log.Fatalf("Failed to read configuration: %v", err) + } + } + return config } diff --git a/flags.go b/flags.go new file mode 100644 index 0000000..11a79c6 --- /dev/null +++ b/flags.go @@ -0,0 +1,15 @@ +package main + +import ( + "flag" +) + +type Flags struct { + ConfigPath string +} + +func (f *Flags) FromArgs() { + flag.StringVar(&f.ConfigPath, "config", "", "path to configuration file") + + flag.Parse() +} diff --git a/main.go b/main.go index 128720f..f06d525 100644 --- a/main.go +++ b/main.go @@ -11,7 +11,10 @@ func main() { log.Println("+++ Started Sia server +++") defer log.Println("--- Stopped Sia server ---") - config := GetStartupConfig() + flags := Flags{} + flags.FromArgs() + + config := GetStartupConfig(flags.ConfigPath) tx := make(chan MQTTMessage) diff --git a/meson.build b/meson.build index 0917410..7436494 100644 --- a/meson.build +++ b/meson.build @@ -9,6 +9,7 @@ sia_server = custom_target( meson.current_source_dir() / 'mqtt.go', meson.current_source_dir() / 'homematic.go', meson.current_source_dir() / 'config.go', + meson.current_source_dir() / 'flags.go', ], output : 'sia-server', command : [ -- cgit v1.2.3-70-g09d2