First implementation of new config format

- Functionally equivalent to old version at present
- Temperature and Humidity sensors not handled yet
- Moved HTTP handlers around
This commit is contained in:
Bendodroid 2024-01-13 23:26:04 +01:00
commit b2f62c7bb0
Signed by: bendodroid
GPG key ID: 3EEE19A0F73D5FFC
7 changed files with 125 additions and 121 deletions

View file

@ -1,11 +1,54 @@
package config
// Configuration represents the settings needed to configure spaceapid
type Configuration struct {
// The HTTP BasicAuth username for door status updates
BAUsername string
// The HTTP BasicAuth password for door status updates
BAPassword string
// The path to the JSON with initial values
TemplatePath string
import (
"bytes"
"encoding/json"
"log"
"os"
"path/filepath"
"slices"
)
const (
envConfigPath = "CONFIG_PATH"
)
// getConfigPath gets the spaceapid configuration from the respective environment variables
func getConfigPath() string {
// JSON template path
configPath, ok := os.LookupEnv(envConfigPath)
if !ok || configPath == "" {
log.Fatalln("Could not retrieve", envConfigPath, "env variable or variable is empty")
}
// Save as absolute path
absConfigPath, err := filepath.Abs(configPath)
if err != nil {
log.Fatalln("Failed converting", configPath, "to absolute path:", err)
}
return absConfigPath
}
// ParseConfiguration returns the config from file
func ParseConfiguration() (conf SpaceapidConfig) {
log.Println("Parsing configuration file")
// Read file
file, err := os.ReadFile(getConfigPath())
if err != nil {
log.Fatalln("Failed reading file:", err)
}
// Parse JSON
dec := json.NewDecoder(bytes.NewReader(file))
dec.DisallowUnknownFields()
err = dec.Decode(&conf)
if err != nil {
log.Fatalln("Could not parse spaceapid config file:", err)
}
// Check if compatible with v14
if !slices.Contains(conf.Response.APICompatibility, "14") {
log.Fatalln("Provided file doesn't specify compatibility with API version 14")
}
return
}