From 73ab5b8214636f9a157b1253ba35bf1a493c06d3 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 15 Jan 2024 12:02:15 -0500 Subject: [PATCH] refactor: add a means of saving the config if any default value is not set --- config/config.go | 40 +++++++++++++++++++++++++++++++++------- 1 file changed, 33 insertions(+), 7 deletions(-) diff --git a/config/config.go b/config/config.go index 4d70767..a5b64c4 100644 --- a/config/config.go +++ b/config/config.go @@ -26,8 +26,6 @@ func Init() error { viper.SetEnvPrefix("LUME_WEB_PORTAL") viper.AutomaticEnv() - defaults() - err := viper.ReadInConfig() if err != nil { if errors.As(err, &viper.ConfigFileNotFoundError{}) { @@ -36,17 +34,45 @@ func Init() error { if err != nil { return err } - return nil + return writeDefaults() } return err } + return writeDefaults() +} + +func writeDefaults() error { + defaults := map[string]interface{}{ + "core.post-upload-limit": 1024 * 1024 * 1000, + "core.log.level": "info", + "protocol.s5.p2p.maxOutgoingPeerFailures": 10, + "protocol.s5.p2p.network": "", + } + + changes := false + + for key, value := range defaults { + if writeDefault(key, value) { + changes = true + } + } + + if changes { + err := viper.WriteConfig() + if err != nil { + return err + } + } + return nil } -func defaults() { - viper.SetDefault("core.post-upload-limit", 1024*1024*1000) - viper.SetDefault("core.log.level", "info") +func writeDefault(key string, value interface{}) bool { + if !viper.IsSet(key) { + viper.SetDefault(key, value) + return true + } - viper.SetDefault("protocol.s5.p2p.maxOutgoingPeerFailures", 10) + return false }