Skip to content

Instantly share code, notes, and snippets.

@affanshahid
Last active October 26, 2023 13:51
Show Gist options
  • Save affanshahid/ed2daff79f13aa61b427abeb894af937 to your computer and use it in GitHub Desktop.
Save affanshahid/ed2daff79f13aa61b427abeb894af937 to your computer and use it in GitHub Desktop.
Using spf13/viper like node-config
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