Skip to content

Instantly share code, notes, and snippets.

@bioform
Forked from affanshahid/viper-like-node-config.go
Created November 2, 2024 20:07
Show Gist options
  • Save bioform/b0674b68cddf44a9bdf67bf54a3139b8 to your computer and use it in GitHub Desktop.
Save bioform/b0674b68cddf44a9bdf67bf54a3139b8 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