"Improve" config loading

This commit is contained in:
Andrew-71 2024-03-20 00:02:22 +03:00
parent fb3a64af33
commit affcef2eda
3 changed files with 20 additions and 16 deletions

View file

@ -21,7 +21,5 @@ COPY pages pages/
VOLUME data VOLUME data
VOLUME config VOLUME config
#USER nonroot:nonroot
EXPOSE 7101 EXPOSE 7101
ENTRYPOINT ["/hibiscus"] ENTRYPOINT ["/hibiscus"]

View file

@ -31,20 +31,17 @@ func (c *Config) Save() error {
return nil return nil
} }
func LoadConfig() (Config, error) { func (c *Config) Reload() error {
cfg := Config{Port: 7101, Username: "admin", Password: "admin"} // Default values are declared here, I guess
if _, err := os.Stat(ConfigFile); errors.Is(err, os.ErrNotExist) { if _, err := os.Stat(ConfigFile); errors.Is(err, os.ErrNotExist) {
err := cfg.Save() err := c.Save()
if err != nil { if err != nil {
return cfg, err return err
} }
return cfg, nil return nil
} }
file, err := os.Open(ConfigFile) file, err := os.Open(ConfigFile)
if err != nil { if err != nil {
log.Fatal(err) return err
} }
defer file.Close() defer file.Close()
@ -57,19 +54,28 @@ func LoadConfig() (Config, error) {
key := entry[0] key := entry[0]
value := entry[1] value := entry[1]
if key == "username" { if key == "username" {
cfg.Username = value c.Username = value
} else if key == "password" { } else if key == "password" {
cfg.Password = value c.Password = value
} else if key == "port" { } else if key == "port" {
numVal, err := strconv.Atoi(value) numVal, err := strconv.Atoi(value)
if err == nil { if err == nil {
cfg.Port = numVal c.Port = numVal
} }
} }
} }
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
log.Fatal(err) return err
} }
return cfg, nil return nil
}
func ConfigInit() Config {
cfg := Config{Port: 7101, Username: "admin", Password: "admin"} // Default values are declared here, I guess
err := cfg.Reload()
if err != nil {
log.Fatal(err)
}
return cfg
} }

View file

@ -1,6 +1,6 @@
package main package main
var Cfg, _ = LoadConfig() var Cfg = ConfigInit()
func main() { func main() {
Serve() Serve()