Last active
November 2, 2024 20:07
-
-
Save affanshahid/ed2daff79f13aa61b427abeb894af937 to your computer and use it in GitHub Desktop.
Using spf13/viper like node-config
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
"github.com/spf13/viper" | |
) | |
// Load reads in configurations from config files and environment variables | |
// It uses the following order to override configurations: | |
// 1. .default.env, 2. .$env.env, 3. .local.env, 4. environment variables | |
func Load(env, configFolderPath string) error { | |
viper.SetConfigName(".default") | |
viper.SetConfigType("env") | |
viper.AddConfigPath(configFolderPath) | |
if err := viper.ReadInConfig(); err != nil { | |
return err | |
} | |
if env != "" { | |
env = strings.ToLower(env) | |
viper.SetConfigName(fmt.Sprintf(".%s", env)) | |
viper.MergeInConfig() | |
} | |
viper.SetConfigName(".local") | |
viper.MergeInConfig() | |
viper.AutomaticEnv() | |
return nil | |
} | |
func main() { | |
s := viper.Get("key") | |
fmt.Println(s) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment