| name | golang-viper |
| description | Go Viper config library (spf13/viper). Use for config files (SetConfigName, AddConfigPath), defaults, env binding (SetEnvPrefix, AutomaticEnv, BindEnv), or struct unmarshaling with mapstructure tags. |
Golang Viper Configuration
Viper is Go's most popular configuration library. It handles config files, environment variables, defaults, and remote config stores with a unified API.
Config Precedence (highest to lowest)
viper.Set() - explicit runtime overrides
- Command-line flags (via pflag)
- Environment variables
- Config files
- Remote key/value stores (etcd, Consul)
viper.SetDefault() - defaults
Quick Reference
viper.SetConfigName("config")
viper.SetConfigType("yaml")
viper.AddConfigPath(".")
viper.AddConfigPath("$HOME/.myapp")
viper.SetDefault("server.port", 8080)
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
} else {
return fmt.Errorf("config error: %w", err)
}
}
host := viper.GetString("server.host")
port := viper.GetInt("server.port")
debug := viper.GetBool("debug")
var config Config
viper.Unmarshal(&config)
viper.UnmarshalKey("server", &config.Server)
Key Behaviors
- Keys are case-insensitive:
server.PORT and server.port are the same
- Env vars ARE case-sensitive:
APP_PORT differs from app_port
- Nested keys use dots:
server.host maps to YAML server: { host: ... }
- Not thread-safe: wrap concurrent access with mutex
References
Detailed documentation for each feature area:
references/core-config.md - Config files, paths, defaults, reading; multiple configs + AllSettings
references/environment-vars.md - Env binding, prefixes, key replacers, AutomaticEnv; gotchas + patterns
references/unmarshaling.md - Structs, mapstructure tags, type getters, custom types; sub-configs, strict mode, gotcha
references/advanced-features.md - Watching changes, remote config, writing configs
Common Patterns
Multiple Config Files (config + secrets)
viper.SetConfigName("config")
viper.ReadInConfig()
secretsViper := viper.New()
secretsViper.SetConfigName("secrets")
secretsViper.AddConfigPath(".")
secretsViper.ReadInConfig()
Environment Variable Override
viper.SetEnvPrefix("MYAPP")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()