map-dots/traccar/config.go

82 lines
1.4 KiB
Go

package traccar
import (
"errors"
"os"
"strings"
)
type cfgParam struct {
EnvVarName string
ConfFilePath string
DefaultValue string
FailIfAbsent bool
}
type cfg struct {
user string
pass string
tUrl string
}
func loadConfig() (*cfg, error) {
cfgParams := map[string]cfgParam{
"user": {
EnvVarName: "TRACCAR_USER",
ConfFilePath: "/mapdots/cfg/traccar-user",
FailIfAbsent: true,
},
"pass": {
EnvVarName: "TRACCAR_PASS",
ConfFilePath: "/mapdots/cfg/traccar-pass",
FailIfAbsent: true,
},
"tUrl": {
EnvVarName: "TRACCAR_URL",
ConfFilePath: "/mapdots/cfg/traccar-url",
},
}
cfg := &cfg{}
for key, param := range cfgParams {
if val, ok := os.LookupEnv(param.EnvVarName); ok {
cfg.setConfigValue(key, string(val))
continue
}
if data, err := os.ReadFile(param.ConfFilePath); err == nil {
cfg.setConfigValue(key, string(data))
continue
}
if param.DefaultValue != "" {
cfg.setConfigValue(key, param.DefaultValue)
continue
}
if param.FailIfAbsent {
return nil, errors.New("Failed to load configuration: " + key + " is required but not set")
}
}
return cfg, nil
}
func (c *cfg) setConfigValue(key, value string) {
stripNewlines := func(s string) string {
return strings.ReplaceAll(s, "\n", "")
}
switch key {
case "user":
c.user = stripNewlines(value)
case "pass":
c.pass = stripNewlines(value)
case "tUrl":
c.tUrl = stripNewlines(value)
}
}