Skip to content

Instantly share code, notes, and snippets.

@alinz
Created January 5, 2020 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alinz/92fd7b56d400b59bc584935ae0ce15b6 to your computer and use it in GitHub Desktop.
Save alinz/92fd7b56d400b59bc584935ae0ce15b6 to your computer and use it in GitHub Desktop.
Viper Config
package config
import (
"os"
"strings"
"github.com/spf13/viper"
)
type Config struct {
Service Service `mapstructure:"service"`
}
// Read reads the CONFIG_PATH environment variable for finding
// the location of config file. In case CONFIG_PATH is not being set
// it returns the default values for config
func Read() (*Config, error) {
var err error
viper := viper.New()
viper.SetConfigName("config")
viper.SetEnvPrefix("RONDO")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
path := os.Getenv("CONFIG_PATH")
if path == "" {
err = viper.ReadConfig(strings.NewReader("{}"))
} else {
viper.AddConfigPath(path)
err = viper.ReadInConfig()
}
if err != nil {
return nil, err
}
config := &Config{}
err = viper.Unmarshal(config)
if err != nil {
return nil, err
}
return config, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment