From 7ef343e871c0053534eab74763c4a48346669976 Mon Sep 17 00:00:00 2001 From: xengineering Date: Mon, 25 Mar 2024 20:04:33 +0100 Subject: Move configuration code to a separate file --- config.go | 42 ++++++++++++++++++++++++++++++++++++++++++ main.go | 37 ------------------------------------- 2 files changed, 42 insertions(+), 37 deletions(-) create mode 100644 config.go diff --git a/config.go b/config.go new file mode 100644 index 0000000..3bb153b --- /dev/null +++ b/config.go @@ -0,0 +1,42 @@ +package main + +import ( + "encoding/json" + "net/netip" + "os" + "log" +) + +type RuntimeConfig struct { + Devices DevicesConfig + Web WebConfig +} + +type DevicesConfig struct { + Hs100 []Hs100Conf +} + +type WebConfig struct { + Listen netip.AddrPort +} + +// parseConfig() parses and validates the runtime configuration file and +// returns it as Go datastructure. +func parseConfig(path string) RuntimeConfig { + data, err := os.ReadFile(path) + if err != nil { + log.Fatalf("Could not read '%s'!", path) + } + + if !json.Valid(data) { + log.Fatalf("%s contains invalid JSON!", path) + } + + config := RuntimeConfig{} + err = json.Unmarshal(data, &config) + if err != nil { + log.Fatalf("Could not parse configuration file:\n%s\n", err) + } + + return config +} diff --git a/main.go b/main.go index 4331123..48a00a5 100644 --- a/main.go +++ b/main.go @@ -1,33 +1,17 @@ package main import ( - "encoding/json" "embed" "flag" "fmt" "log" "net/http" - "net/netip" - "os" "text/template" ) //go:embed simple.css/simple.css templates/index.html var static embed.FS -type RuntimeConfig struct { - Devices DevicesConfig - Web WebConfig -} - -type DevicesConfig struct { - Hs100 []Hs100Conf -} - -type WebConfig struct { - Listen netip.AddrPort -} - func main() { configPath := parseFlags() c := parseConfig(configPath) @@ -51,27 +35,6 @@ func parseFlags() string { return r } -// parseConfig() parses and validates the runtime configuration file and -// returns it as Go datastructure. -func parseConfig(path string) RuntimeConfig { - data, err := os.ReadFile(path) - if err != nil { - log.Fatalf("Could not read '%s'!", path) - } - - if !json.Valid(data) { - log.Fatalf("%s contains invalid JSON!", path) - } - - config := RuntimeConfig{} - err = json.Unmarshal(data, &config) - if err != nil { - log.Fatalf("Could not parse configuration file:\n%s\n", err) - } - - return config -} - // index() returns a HTTP handler for the index page. func index(devices DevicesConfig) func(http.ResponseWriter, *http.Request) { tmpl, err := template.ParseFS(static, "templates/index.html") -- cgit v1.2.3-70-g09d2