Generated banner for Golang Spf13 Viper
Generated logo for Golang Spf13 Viper

Golang Spf13 Viper

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Tool integration
  • Software development
  • MIT
  • No issues found

From the author

Golang configuration library using spf13/viper — layered precedence (flag > env > file > KV > default), BindPFlag/BindPFlags, SetEnvPrefix + SetEnvKeyReplacer + AutomaticEnv, ReadInConfig + ConfigFileNotFoundError, Unmarshal + mapstructure struct tags, Sub for sub-trees, WatchConfig + OnConfigChange for hot reload, viper.New() for test isolation, and remote KV integration. Apply when using or adopting spf13/viper, or when the codebase imports `github.com/spf13/viper`. For CLI command structure alongside viper, see the `samber/cc-skills-golang@golang-spf13-cobra` skill. For general CLI architecture, see `samber/cc-skills-golang@golang-cli`.
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

Viper is a comprehensive configuration solution for Go applications that resolves values from multiple sources including defaults, config files, environment variables, flags, and remote KV stores. It implements a strict precedence pipeline, ensuring that configuration values are retrieved in a predictable order. This skill provides guidance on integrating Viper into Go projects, handling environment variable binding, mapping configurations to structs, and managing hot reloads.

What it does

  • Resolves configuration values based on a fixed precedence order (flags > env > file > KV > defaults).
  • Supports multiple configuration file formats including YAML, JSON, TOML, and HCL.
  • Maps complex configuration structures into Go structs using mapstructure tags.
  • Enables hot reloading of configuration files via filesystem notifications.
  • Provides isolation for unit tests by supporting per-test Viper instances.
  • Integrates with CLI frameworks like Cobra to bind command-line flags to configuration keys.

When to use it

  • When your Go application requires configuration from multiple sources.
  • When you need to support environment-specific overrides for application settings.
  • When building CLI tools that require both command-line flags and persistent configuration files.
  • When you need to watch for configuration changes at runtime without restarting the service.

Advantages

  • Centralizes configuration logic, reducing boilerplate code for reading settings.
  • Provides a consistent API for accessing configuration regardless of the source.
  • Prevents configuration shadowing bugs through a well-defined precedence pipeline.
  • Simplifies testing by allowing isolated configuration states.

Usage examples

“How do I set up Viper to read from a YAML file and environment variables?”
The agent will provide code to set the config name, add search paths, configure the environment prefix and key replacer, and call ReadInConfig.
“How do I bind a Cobra flag to a Viper configuration key?”
The agent will demonstrate using viper.BindPFlag within the init() function or PersistentPreRunE to link a specific flag to a configuration key.
“How should I unmarshal my configuration into a struct?”
The agent will show how to define a struct with mapstructure tags and use viper.Unmarshal to populate it safely.
“How do I test my code without using the global Viper instance?”
The agent will explain how to instantiate a new Viper object using viper.New() within each test case to ensure isolation.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-spf13-viper/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-spf13-viper.zip -d .agents/skills

Documentation by samber

Persona: You are a Go engineer who treats configuration as a layered system. Flag beats env beats file beats default — and you bind every key so all four layers stay reachable through one API.

Using spf13/viper for layered configuration in Go

Viper resolves configuration values from multiple sources in a fixed precedence order. It has no user-facing surface — it doesn't define commands or flags. Its job is to answer "what is the value of key X right now?" by walking its source layers from highest to lowest priority.

Official Resources:

This skill is not exhaustive — refer to library documentation and code examples for more information:

  • For Go package docs, symbols, versions, importers, and known vulnerabilities, → See samber/cc-skills-golang@golang-pkg-go-dev skill (godig), preferred over Context7 for Go package facts.

  • To navigate this library's usage in your own code (definitions, call sites, diagnostics), → See samber/cc-skills-golang@golang-gopls skill (gopls).

  • Context7 remains a fallback for docs not indexed on pkg.go.dev.

go get github.com/spf13/viper@latest

Viper vs. cobra

Cobra owns the command tree — subcommands, flags, arg validation, completions. Viper owns configuration resolution — it answers "what is the value of key X?" by walking its source layers, with no user-facing surface of its own: it is purely a key-value resolver.

  • Cobra alone — flag-only CLIs.

  • Viper alone — config-file daemons.

  • Both — bind flags at PersistentPreRunE via BindPFlag.

→ See samber/cc-skills-golang@golang-spf13-cobra for the cobra side of this integration.

The precedence pipeline

Viper resolves a key by walking sources in this order (first set value wins):

1. explicit Set()      — viper.Set("key", val)    highest priority
2. flag                — bound pflag.Flag
3. env var             — BindEnv / AutomaticEnv
4. config file         — ReadInConfig / MergeInConfig
5. KV remote           — etcd / Consul
6. default             — viper.SetDefault("key", val)   lowest priority

This pipeline is fixed and cannot be reordered. Understanding it prevents most viper bugs: a key that "should" come from a config file may be shadowed by an env var or a flag with a default value.

Sources and config files

viper.SetConfigName("config")
viper.AddConfigPath("$HOME/.myapp")
if err := viper.ReadInConfig(); err != nil {
    var notFound *viper.ConfigFileNotFoundError
    if !errors.As(err, &notFound) {
        return fmt.Errorf("reading config: %w", err) // propagate real errors only
    }
}

ConfigFileNotFoundError must be handled gracefully — config files are usually optional. An unhandled error from a missing file crashes programs that are perfectly valid when run with only flags or env vars.

For supported formats (JSON, TOML, YAML, HCL, INI, properties), MergeInConfig, and remote KV, see sources-and-formats.md.

Env binding and key replacers

This is the highest-bug-density area in viper. All three settings must be wired together — missing any one breaks nested key resolution:

// ✓ Good — all three wired together at startup
viper.SetEnvPrefix("MYAPP")                             // prevent collisions: PORT → MYAPP_PORT
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))  // database.host → MYAPP_DATABASE_HOST
viper.AutomaticEnv()

// ✗ Bad — without SetEnvKeyReplacer, viper looks for MYAPP_DATABASE.HOST (dot preserved)

For BindEnv, AllowEmptyEnv, and env-vs-default interaction, see binding-and-env.md.

Flag binding (the cobra seam)

Bind cobra flags to viper in init() or PersistentPreRunE — never in RunE (config loading in PersistentPreRunE already ran before RunE, so bindings set in RunE are missed):

func init() {
    rootCmd.PersistentFlags().Int("port", 8080, "listen port")
    viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))
    // viper.BindPFlags(cmd.Flags()) — bind an entire FlagSet at once
}

For AllowEmptyEnv and flag/env interaction details, see binding-and-env.md.

Unmarshaling into structs

viper.Unmarshal maps the resolved configuration into a struct using mapstructure:

type Config struct {
    Port     int `mapstructure:"port"`
    Database struct {
        MaxConn int `mapstructure:"max_conn"` // explicit tag: mapstructure won't convert underscore→camelCase
    } `mapstructure:"database"`
}
var cfg Config
viper.Unmarshal(&cfg)

Always use mapstructure tags — implicit mapping is fragile for nested structs and underscore-named fields. Prefer UnmarshalKey("database", &dbCfg) over Sub("database").Unmarshal — it avoids the nil-check Sub requires when the key is missing.

For time.Duration / net.IP / slice decoders and custom DecodeHook registration, see unmarshal.md.

Sub-trees

viper.Sub("database") returns a new *viper.Viper scoped to the prefix, or nil if the key does not exist — always nil-check before calling methods on the result. Prefer UnmarshalKey("database", &dbCfg) which avoids the nil risk entirely.

Hot reload

viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) { /* re-apply changed values */ })

WatchConfig uses fsnotify and watches inodes, so editors that write atomically via rename (vim, neovim) replace the inode and the callback may not fire. Test hot-reload with echo >> config.yaml, not editor saves. For race-safe reload patterns, see watch-and-reload.md.

Test isolation

Never use the global viper in tests — state leaks across test cases. Use viper.New() per test so each instance is isolated:

v := viper.New()
v.SetConfigFile("testdata/config.yaml")
require.NoError(t, v.ReadInConfig())

For t.Setenv interactions and Reset() limitations, see testing-and-isolation.md.

Best Practices

  1. Set prefix + key replacer + AutomaticEnv together — missing any one causes nested env keys to silently not resolve (database.host → DATABASE.HOST instead of DATABASE_HOST).

  2. Handle ConfigFileNotFoundError gracefully — a missing config file should not crash a service that runs with only flags and env vars.

  3. Always use mapstructure tags on config structs — implicit mapping silently misses nested and underscore-named fields.

  4. Use viper.New() in tests, never the global — the global accumulates state across test runs; per-test instances are isolated.

  5. Bind flags before Execute() — binding in RunE is too late; cobra parses flags before RunE runs.

Common Mistakes

MistakeWhy it failsFix
AutomaticEnv without SetEnvKeyReplacerdatabase.host looks for MYAPP_DATABASE.HOST (dot preserved) — never matchesAdd SetEnvKeyReplacer(strings.NewReplacer(".", "_")) before AutomaticEnv
No mapstructure tags on struct fieldsSilently misses nested and underscore-named fieldsAdd mapstructure:"key_name" to every field
Using global viper in testsState from one test contaminates the next, causing flaky orderingCreate viper.New() per test
Missing ConfigFileNotFoundError checkMissing config file crashes a service that should run on flags/env aloneerrors.As(err, &notFound) — only propagate non-not-found errors

Further Reading

  • sources-and-formats.md — supported file formats, multi-path search, MergeInConfig, remote KV (etcd/Consul)

  • binding-and-env.md — BindEnv, AutomaticEnv, SetEnvPrefix, SetEnvKeyReplacer, AllowEmptyEnv, timing rules

  • unmarshal.md — Unmarshal, UnmarshalKey, mapstructure tags, custom DecodeHooks (Duration, IP, slice)

  • watch-and-reload.md — WatchConfig, OnConfigChange, fsnotify caveats, atomic-rename trap, race-safe patterns

  • testing-and-isolation.md — viper.New() per test, t.Setenv interactions, Reset() limitations, snapshot/restore

Cross-References

  • → See samber/cc-skills-golang@golang-cli skill for general CLI architecture — project layout, exit codes, signal handling, cobra+viper integration

  • → See samber/cc-skills-golang@golang-spf13-cobra skill for the cobra side of this integration (flag definition and binding)

  • → See samber/cc-skills-golang@golang-testing skill for general Go testing patterns

If you encounter a bug or unexpected behavior in spf13/viper, open an issue at https://github.com/spf13/viper/issues.

Files

references/binding-and-env.md

Viper Env Binding and Flag Binding

Table of Contents

  • The binding interaction model

  • AutomaticEnv vs BindEnv

  • SetEnvKeyReplacer in depth

  • AllowEmptyEnv

  • Flag binding

  • How pflag binding interacts with precedence

  • Debugging binding

The binding interaction model

Three settings control how viper maps environment variables to keys. They must be set together:

viper.SetEnvPrefix("MYAPP")                           // adds MYAPP_ prefix
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) // database.host → MYAPP_DATABASE_HOST
viper.AutomaticEnv()                                   // activates auto-binding

Call these before any ReadInConfig or viper.Get* call — typically in a root command's PersistentPreRunE or in init().

AutomaticEnv vs BindEnv

MethodBehavior
AutomaticEnv()Every key is automatically mapped to its env equivalent (with prefix and replacer applied)
BindEnv(key, envVars...)Only the specified key is bound, to the specified env var name(s)

Use AutomaticEnv for the common case. Use BindEnv when you need to bind to an env var with a name that doesn't follow your prefix/replacer convention (e.g., third-party env vars like GOOGLE_APPLICATION_CREDENTIALS).

// Bind a specific non-prefixed env var
viper.BindEnv("google.credentials", "GOOGLE_APPLICATION_CREDENTIALS")

SetEnvKeyReplacer in depth

Viper keys use . as separator for nested values. Env vars cannot contain dots. The replacer maps between them.

// Config file:
// database:
//   host: localhost
//   max_conn: 25

// Without replacer:
viper.SetEnvPrefix("MYAPP")
viper.AutomaticEnv()
viper.GetString("database.host")  // looks for MYAPP_DATABASE.HOST — no match

// With replacer:
viper.SetEnvPrefix("MYAPP")
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
viper.AutomaticEnv()
viper.GetString("database.host")  // looks for MYAPP_DATABASE_HOST — matches

The replacer operates on the viper key before prepending the prefix, so the lookup chain is: database.host → replace . with _ → database_host → prepend prefix → MYAPP_DATABASE_HOST.

AllowEmptyEnv

By default, viper ignores env vars set to the empty string — the empty string is treated as "not set" and viper continues down the precedence stack. Override this behavior:

viper.AllowEmptyEnv(true)
// now MYAPP_PORT="" → viper.GetInt("port") == 0, not the default

Flag binding

Bind a pflag after defining it:

func init() {
    rootCmd.PersistentFlags().Int("port", 8080, "listen port")
    viper.BindPFlag("port", rootCmd.PersistentFlags().Lookup("port"))
}

Bind an entire flag set:

viper.BindPFlags(rootCmd.PersistentFlags())

Timing rule: Bind flags in init() or in PersistentPreRunE. The binding call must happen before Execute() parses flags — specifically, before any viper.Get* call on a flag-backed key. Binding after Execute() causes the flag's Changed state to be unknown, so viper may not promote the flag value to the correct precedence layer.

How pflag binding interacts with precedence

Viper checks flag.Changed (whether the user explicitly passed the flag). This is how it distinguishes between "flag default" (low priority) and "flag explicitly set" (high priority):

  • flag.Changed == false (flag has its default): viper treats the flag as not present and falls through to env/file/default.

  • flag.Changed == true (flag was provided on the command line): viper treats the flag value as the highest-priority source.

This means viper.GetInt("port") correctly returns the flag value when --port 9090 is passed, and falls back to env MYAPP_PORT or config file port: 8080 otherwise.

Debugging binding

Print all resolved values to verify your binding is correct:

fmt.Println(viper.AllSettings())
// map[database:map[host:localhost max_conn:25] port:8080]

Check env var resolution:

os.Setenv("MYAPP_PORT", "9090")
viper.AutomaticEnv()
fmt.Println(viper.GetInt("port"))  // 9090

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter

The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-spf13-viper · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-spf13-viper.zip