GoLang 12factor config with viper
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 ( | |
"github.com/spf13/viper" | |
"sync" | |
) | |
var instance *Config | |
var once sync.Once | |
func Of() *Config { | |
once.Do(func() { | |
Load() | |
}) | |
return instance | |
} | |
func Load() { | |
vp := viper.New() | |
// follow 12 factors principles https://www.12factor.net/config | |
vp.AutomaticEnv() | |
// just for development environment | |
vp.SetConfigName("development.env") | |
vp.SetConfigType("env") | |
vp.AddConfigPath(".") | |
vp.ReadInConfig() | |
vp.Unmarshal(&instance) | |
} | |
// Mock this method is used to mock the config | |
// only for testing purpose | |
func Mock(v *viper.Viper) { | |
v.Unmarshal(&instance) | |
} | |
type Config struct { | |
Port string `env:"PORT"` | |
Nest NestConfig `env:"NestConfig"` | |
} | |
type NestConfig struct { | |
MarsenNo int `env:"MarsenNo"` | |
MarsenFlag bool `env:"MarsenFlag"` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment