A Go service in production reads its config from at least three places — a YAML file, a few environment variables, and CLI flags from systemd. Hand-rolling that merge is annoying and gets every cohort of developers to invent slightly different precedence rules. Viper does the merging once and right, with a precedence chain you can document. This article shows the Viper layout Stack Harbor uses on Go services we operate.
How to verify
After wiring Viper, dump the resolved config to confirm precedence:
go run . config dump
LOG_LEVEL=debug go run . config dump
go run . --log-level=warn config dump
A config dump subcommand reading viper.AllSettings() and printing it as JSON is invaluable for “why is this value not what I set?” debugging.
What’s happening
Viper merges configuration from many sources into one logical map, applying a fixed precedence: explicit Set() calls override CLI flags override environment variables override config file override key/value remote override defaults. You write code as if reading from a single store; Viper handles the merge.
The merge happens lazily. viper.GetString("server.host") walks the precedence chain at call time, which means changing an env var after process start can be picked up if Viper is configured with AutomaticEnv(). File watching is opt-in via WatchConfig() plus an OnConfigChange callback.
Viper’s secret-handling weakness is well known: it stores secrets in memory as plain strings, and dumping AllSettings exposes them. The standard pattern is to keep secrets OUT of the config file and IN env vars or a secret store, then load them into the same Viper tree.
The procedure
-
Install Viper and define a config struct.
go get github.com/spf13/viper// internal/config/config.go package config type Config struct { Server struct { Host string `mapstructure:"host"` Port int `mapstructure:"port"` } `mapstructure:"server"` DB struct { URL string `mapstructure:"url"` } `mapstructure:"db"` Log struct { Level string `mapstructure:"level"` } `mapstructure:"log"` } -
Load with precedence.
func Load() (Config, error) { v := viper.New() v.SetConfigName("config") v.SetConfigType("yaml") v.AddConfigPath("/etc/myapp") v.AddConfigPath(".") v.SetEnvPrefix("MYAPP") v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.AutomaticEnv() v.SetDefault("server.host", "0.0.0.0") v.SetDefault("server.port", 8080) v.SetDefault("log.level", "info") if err := v.ReadInConfig(); err != nil { if _, ok := err.(viper.ConfigFileNotFoundError); !ok { return Config{}, fmt.Errorf("read config: %w", err) } } var cfg Config if err := v.Unmarshal(&cfg); err != nil { return Config{}, fmt.Errorf("unmarshal: %w", err) } return cfg, nil }MYAPP_SERVER_HOST(env) overridesserver.host(YAML) overrides the default. The dot-to-underscore replacer is required because env vars cannot contain dots. -
Author a
config.yaml.server: host: 127.0.0.1 port: 8080 db: url: ${DB_URL} # NOT expanded by Viper - left as literal log: level: infoViper does NOT expand
${VAR}references inside config values. Use env-var precedence instead — setMYAPP_DB_URLto override. -
Bind to Cobra flags. A Cobra root command can register pflags that Viper picks up:
var rootCmd = &cobra.Command{ Use: "myapp", ... } func init() { rootCmd.PersistentFlags().String("log-level", "", "Log level") _ = viper.BindPFlag("log.level", rootCmd.PersistentFlags().Lookup("log-level")) }Now
--log-level=warnon the CLI wins over both env and YAML. -
Hot-reload on config change. Useful for log levels and feature flags:
v.WatchConfig() v.OnConfigChange(func(e fsnotify.Event) { slog.Info("config changed", "file", e.Name) reloadDynamic(v) })reloadDynamiconly updates settings that are safe to change at runtime — log level, sampling rate, rate-limit thresholds. Database URL or listen port require a restart. -
Secrets via env vars only. A defensible pattern:
# /etc/systemd/system/myapp.service [Service] EnvironmentFile=/etc/myapp/secrets.env ExecStart=/usr/bin/myapp serve# /etc/myapp/secrets.env (root:0600) MYAPP_DB_URL=postgres://app:CHANGEME@db.internal/app MYAPP_JWT_SECRET=...The YAML file holds the boring values; secrets stay in the env file owned by root, mode 0600. The systemd unit pulls both together.
-
Dump config for debugging. A subcommand that prints
viper.AllSettings():var configDumpCmd = &cobra.Command{ Use: "config dump", RunE: func(cmd *cobra.Command, args []string) error { out, _ := json.MarshalIndent(viper.AllSettings(), "", " ") fmt.Println(string(out)) return nil }, }This is the single most useful debug command — every “I set the env var but it does not take” turns into a
config dumpand an obvious-in-hindsight explanation.
Common pitfalls
- Env-var case mismatch.
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))is required, otherwise nested keys (server.host) cannot map to env vars. Unmarshalsilently drops unknown keys. Passviper.DecoderConfigOption(func(c *mapstructure.DecoderConfig) { c.ErrorUnused = true })to catch typos likeserer:instead ofserver:.AllSettings()exposes secrets. Never log it without filtering. The dump subcommand should redact keys named*secret*,*password*,*token*.- File-not-found at startup is a config bug. Decide whether the file is required. Treating
ConfigFileNotFoundErroras fatal vs benign is environment-specific — be explicit. WatchConfigreloads the whole tree. If you have non-reloadable settings (like a listen port), guard the OnConfigChange callback so a typo does not partially break the running service.
Stack Harbor keeps configuration deliberately three-tier — defaults in code, YAML for the boring values, env vars for secrets — on every Go service we operate. See how that fits into our managed operations practice when production config drift becomes a recurring incident driver.