diff options
author | xengineering <me@xengineering.eu> | 2024-03-25 20:04:33 +0100 |
---|---|---|
committer | xengineering <me@xengineering.eu> | 2024-03-25 20:04:33 +0100 |
commit | 7ef343e871c0053534eab74763c4a48346669976 (patch) | |
tree | 3c4b8180a9d75556772ce94571f12359f3e1522b | |
parent | 18b533f3b5dbb190d5d6f8769c5f7ef6052e0545 (diff) | |
download | webiot-7ef343e871c0053534eab74763c4a48346669976.tar webiot-7ef343e871c0053534eab74763c4a48346669976.tar.zst webiot-7ef343e871c0053534eab74763c4a48346669976.zip |
Move configuration code to a separate file
-rw-r--r-- | config.go | 42 | ||||
-rw-r--r-- | main.go | 37 |
2 files changed, 42 insertions, 37 deletions
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 +} @@ -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") |