From 2facce8a43f4f6e17296544647a20a527506860e Mon Sep 17 00:00:00 2001 From: Christian Claus Date: Wed, 11 Apr 2018 13:30:28 +0200 Subject: [PATCH] Add abilities for config live reload and user updates --- app/config.go | 34 ++++++++++++++++++++++++++++++++++ app/security.go | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/app/config.go b/app/config.go index 9e79738..622ca70 100644 --- a/app/config.go +++ b/app/config.go @@ -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 } diff --git a/app/security.go b/app/security.go index 81d78d7..357c738 100644 --- a/app/security.go +++ b/app/security.go @@ -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 "" } }