Add abilities for config live reload and user updates

This commit is contained in:
Christian Claus 2018-04-11 13:30:28 +02:00
parent a7b2b18f49
commit 2facce8a43
2 changed files with 35 additions and 1 deletions

View file

@ -5,6 +5,7 @@ import (
"github.com/spf13/viper"
"log"
"os"
"github.com/fsnotify/fsnotify"
)
// Config represents the configuration of the server application.
@ -57,6 +58,39 @@ func ParseConfig() *Config {
}
}
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
file, err := os.Open(e.Name)
if err != nil {
fmt.Println("Error reloading config", e.Name)
}
var updatedCfg = &Config{}
viper.ReadConfig(file)
viper.Unmarshal(&updatedCfg)
for k, _ := range cfg.Users {
if updatedCfg.Users[k] == nil {
fmt.Printf("Removed User from configuration: %s\n", k)
cfg.Users[k] = nil
}
}
for k, v := range updatedCfg.Users {
if cfg.Users[k] == nil {
fmt.Printf("Added User to configuration: %s\n", k)
cfg.Users[k] = v
} else {
if cfg.Users[k].Password != v.Password {
fmt.Printf("Updated password of user: %s\n", k)
cfg.Users[k].Password = v.Password
}
}
}
})
return cfg
}

View file

@ -16,7 +16,7 @@ func Authorize(config *Config) auth.SecretProvider {
return user.Password
}
fmt.Printf("Username not found: %s", username)
fmt.Printf("Username not found: %s\n", username)
return ""
}
}