Created
January 5, 2020 14:40
-
-
Save alinz/92fd7b56d400b59bc584935ae0ce15b6 to your computer and use it in GitHub Desktop.
Viper 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 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