samber/cc-skills-golang / skills/golang-spf13-viper
golang-spf13-viper
VerifiedGolang 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`.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 10.0 KB |
| evals/evals.json | config | 21.0 KB |
| references/binding-and-env.md | markdown | 4.2 KB |
| references/sources-and-formats.md | markdown | 3.7 KB |
| references/testing-and-isolation.md | markdown | 4.1 KB |
| references/unmarshal.md | markdown | 4.4 KB |
| references/watch-and-reload.md | markdown | 3.5 KB |
references/unmarshal.md
View on GitHub# Viper Unmarshal and Struct Mapping
## Table of Contents
- [Basic Unmarshal](#basic-unmarshal)
- [mapstructure tags](#mapstructure-tags)
- [UnmarshalKey — extracting a sub-tree](#unmarshalkey--extracting-a-sub-tree)
- [time.Duration](#timeduration)
- [net.IP and custom types](#netip-and-custom-types)
- [Squash for embedded structs](#squash-for-embedded-structs)
- [Remain for unknown keys](#remain-for-unknown-keys)
- [Weak decoding](#weak-decoding)
## Basic Unmarshal
```go
type Config struct {
Port int `mapstructure:"port"`
Host string `mapstructure:"host"`
LogLevel string `mapstructure:"log_level"`
Database struct {
DSN string `mapstructure:"dsn"`
MaxConn int `mapstructure:"max_conn"`
} `mapstructure:"database"`
}
var cfg Config
if err := viper.Unmarshal(&cfg); err != nil {
return fmt.Errorf("decoding config: %w", err)
}
```
## mapstructure tags
Always use `mapstructure` tags. Without them, mapstructure falls back to case-insensitive field name matching, which works for simple cases but silently fails for:
- Nested structs where the outer key uses an underscore (`max_conn` → `MaxConn`)
- Unexported fields
- Fields where the Go name does not match the config key
```go
// ✓ Good — explicit and immune to rename surprises
type TLSConfig struct {
CertFile string `mapstructure:"cert_file"`
KeyFile string `mapstructure:"key_file"`
Enabled bool `mapstructure:"enabled"`
}
// ✗ Fragile — relies on case-folding; breaks when config key uses underscores
type TLSConfig struct {
CertFile string // viper key "certfile" or "CertFile", not "cert_file"
KeyFile string
Enabled bool
}
```
## UnmarshalKey — extracting a sub-tree
```go
type DatabaseConfig struct {
DSN string `mapstructure:"dsn"`
MaxConn int `mapstructure:"max_conn"`
}
var dbCfg DatabaseConfig
if err := viper.UnmarshalKey("database", &dbCfg); err != nil {
return fmt.Errorf("decoding database config: %w", err)
}
```
Prefer `UnmarshalKey` over `viper.Sub` + `Unmarshal` — fewer nil checks and less boilerplate.
## time.Duration
Viper's `GetDuration` parses duration strings (`"1h30m"`, `"500ms"`) from config files and env vars. When using `Unmarshal`, mapstructure does not know how to decode a duration string into `time.Duration` by default.
Register a decode hook:
```go
import "github.com/mitchellh/mapstructure"
var cfg Config
err := viper.Unmarshal(&cfg, func(dc *mapstructure.DecoderConfig) {
dc.DecodeHook = mapstructure.ComposeDecodeHookFunc(
mapstructure.StringToTimeDurationHookFunc(),
mapstructure.StringToSliceHookFunc(","),
dc.DecodeHook,
)
})
```
`StringToTimeDurationHookFunc` handles `"1h30m"` → `time.Duration`. `StringToSliceHookFunc(",")` handles `"a,b,c"` → `[]string{"a", "b", "c"}`.
## net.IP and custom types
```go
import "github.com/mitchellh/mapstructure"
func stringToIPHookFunc() mapstructure.DecodeHookFunc {
return func(f reflect.Type, t reflect.Type, data interface{}) (interface{}, error) {
if f.Kind() != reflect.String || t != reflect.TypeOf(net.IP{}) {
return data, nil
}
ip := net.ParseIP(data.(string))
if ip == nil {
return nil, fmt.Errorf("invalid IP address: %s", data)
}
return ip, nil
}
}
```
## Squash for embedded structs
```go
type BaseConfig struct {
LogLevel string `mapstructure:"log_level"`
Debug bool `mapstructure:"debug"`
}
type ServerConfig struct {
BaseConfig `mapstructure:",squash"` // merge BaseConfig fields at this level
Port int `mapstructure:"port"`
}
```
Without `,squash`, the base config must be nested under a `baseconfig` key in the config file.
## Remain for unknown keys
```go
type Config struct {
Port int `mapstructure:"port"`
Remain map[string]interface{} `mapstructure:",remain"`
}
```
Extra keys from the config file are collected in `Remain` instead of being silently dropped. Useful for forward compatibility.
## Weak decoding
Enable weak type decoding (e.g., string `"true"` → bool `true`) when working with env vars that are always strings:
```go
var cfg Config
err := viper.Unmarshal(&cfg, func(dc *mapstructure.DecoderConfig) {
dc.WeaklyTypedInput = true
})
```
Use with caution — weak decoding can hide bugs where a wrong value type is silently converted.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |