go-spf13-viper
Configuration management with spf13/viper. Covers layered precedence (flags > env > files), binding, unmarshaling, and hot reloading.
SKILL.mdskills/go/go-spf13-viper/SKILL.md
GitHubPrecedence Order
Viper resolves keys by checking sources in this specific order (highest priority first):
- Explicit
Set:viper.Set("port", 8080) - Flags: Bound via
BindPFlagfrom Cobra. - Environment Variables:
SetEnvPrefix,AutomaticEnv. - Config Files: YAML, JSON, TOML, etc.
- Key/Value Remote Store: Etcd, Consul.
- Default Values:
viper.SetDefault("port", 8080).
Best Practices
- Set Prefix and Replacer — Always use
SetEnvPrefixto avoid name collisions andSetEnvKeyReplacer(strings.NewReplacer(".", "_"))to support nested keys in environment variables (e.g.,DB.HOSTbecomesMYAPP_DB_HOST). - Handle File Not Found — Don't fail the app if the config file is missing; many environments (like CI or Docker) might rely solely on environment variables.
- Use
mapstructureTags — When unmarshaling into a struct, always provide explicit tags. Viper doesn't handle casing perfectly by default. - Test Isolation — Never use the global
viperinstance in tests. It creates state leakage between test cases. Useviper.New()instead. - Bind Early — Bind Cobra flags to Viper in
init()orPersistentPreRunE.
Configuration Example
func initConfig() {
v := viper.New() // isolated instance for testability
v.SetConfigName("config")
v.AddConfigPath(".")
v.SetEnvPrefix("APP")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
log.Fatalf("error reading config: %s", err)
}
}
}
Unmarshaling into a Struct
type Config struct {
Port int `mapstructure:"port"`
DB struct {
Host string `mapstructure:"host"`
User string `mapstructure:"user"`
} `mapstructure:"db"`
}
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
log.Fatalf("unable to decode into struct: %v", err)
}
Binding to Cobra Flags
func init() {
rootCmd.PersistentFlags().Int("port", 8080, "App port")
viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))
}
Anti-patterns
- ❌
AutomaticEnv()without a Replacer — Nested config keys won't be reachable via environment variables. - ❌ Hardcoding the Global
viper— Makes unit tests for configuration logic impossible to run in parallel. - ❌ Crashing on missing config file — Prevents users from running the app with just flags or env vars.
- ❌ Implicit struct mapping — Missing
mapstructuretags leads to fields being silently ignored or incorrectly mapped. - ❌ Binding flags in
RunE— Binding happens after flags are parsed, so the bound values won't be available to Viper during execution.