Skip to content

Instantly share code, notes, and snippets.

@marsen

marsen/config.go Secret

Created Jul 20, 2022
Embed
What would you like to do?
GoLang 12factor config with viper
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