К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

golang-spf13-viper — скилл для Claude Code: что делает

Скилл помогает настроить библиотеку spf13/viper в проектах на Go с учётом приоритетов конфигурации, привязки переменных окружения и флагов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add samber/cc-skills-golang --skill golang-spf13-viper -a claude-code
Открыть на GitHub

Что делает golang-spf13-viper

Скилл задаёт правила работы с библиотекой spf13/viper в Go. Он следит за жёстким порядком приоритетов: явный Set(), флаги, переменные окружения, файл настроек, удалённое KV-хранилище и значения по умолчанию. При парсинге файлов ошибок из-за отсутствия конфигурации можно избежать с помощью ConfigFileNotFoundError.

Для корректной работы с переменными окружения скилл связывает SetEnvPrefix, SetEnvKeyReplacer и AutomaticEnv. Без реплейсера точки не превратятся в подчёркивания. Для интеграции с флагами Cobra привязку нужно вызывать в init() или PersistentPreRunE, но ни в коем случае не в RunE.

При маппинге структур скилл требует использовать теги mapstructure и отдавать предпочтение UnmarshalKey. Для отслеживания изменений через WatchConfig помните, что fsnotify следит за inode: редакторы вроде Vim перезаписывают файл через rename, из-за чего колбэк не сработает.

Какие задачи решает

  • связать флаги Cobra с ключами Viper через BindPFlag
  • настроить чтение переменных окружения с префиксами и заменой точек
  • распарсить конфигурацию в структуры через теги mapstructure
  • обработать отсутствие конфигурационного файла через ConfigFileNotFoundError

Примеры запросов агенту

  • Помоги настроить spf13/viper вместе с флагами Cobra для CLI-приложения.
  • Настрой считывание вложенных переменных окружения через SetEnvKeyReplacer в Go.
  • Распарси конфиг YAML в структуру Go с использованием mapstructure.

Как установить golang-spf13-viper

1Через Skills CLI (Vercel)

npx skills add samber/cc-skills-golang --skill golang-spf13-viper -a claude-code

2Вручную: положить файлы

~/.claude/skills/golang-spf13-viper/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/golang-spf13-viper/

Из того же набора32

Весь набор →
golang-code-style samber Скилл помогает писать понятный код на Go, разбирая правила длины строк, объявления переменных, управления потоком выполнения и комментариев. Пригодится при написании и ревью кода, обсуждении стилистики или установке стандартов проекта. Claude Code CX Codex Cursor +1 44 000установок golang-error-handling samber Скилл для идиоматичной обработки ошибок в Go: оборачивание с контекстом, проверка цепочек, структурированное логирование и интеграция с samber/oops. Применяется при создании, оборачивании, инспекции и логировании ошибок. Claude Code CX Codex Cursor +1 43 200установок golang-security samber Находит уязвимости в коде на Go, выстраивает аудит по STRIDE и DREAD и помогает закрывать инъекции, утечки секретов и ошибки в криптографии. Claude Code CX Codex Cursor +1 42 100установок golang-design-patterns samber Скилл подсказывает идиоматичные Go-паттерны для API, жизненного цикла ресурсов, graceful shutdown и архитектуры. Пригодится при проектировании и ревью кода. Claude Code CX Codex Cursor +1 41 900установок golang-performance samber Помогает находить и устранять узкие места в Go-коде: сокращает аллокации памяти, оптимизирует горячие циклы и проверяет результаты замеров. Claude Code CX Codex Cursor +1 41 800установок golang-concurrency samber Скилл задаёт правила для конкурентного кода на Go: жизненный цикл горутин, каналы и select, мьютексы, errgroup, singleflight, воркер-пулы и fan-out/fan-in пайплайны. Claude Code CX Codex Cursor +1 41 600установок golang-database samber Набор правил для работы с реляционными базами данных в Go через database/sql, sqlx и pgx. Помогает писать запросы без ORM и проверять утечки соединений. Claude Code CX Codex Cursor +1 40 700установок golang-naming samber Скилл задаёт правила имён в Go: пакеты, типы, ошибки, булевы поля и тесты. Пригодится при написании, ревью и рефакторинге кода. Claude Code CX Codex Cursor +1 40 700установок

Похожие

finding-google-skills официальный Google LLC Скилл подбирает нужный скилл из каталога Google для выбора или настройки части стека. Пригодится, когда в задаче фигурирует продукт Google или нужно сравнить варианты платформы. Claude Code Gemini CLI CX Codex 4 200установок python-anti-patterns Seth Hobson Скилл-чеклист по типичным ошибкам в Python: разбирает код перед мержем и ловит грабли заранее. Пригодится на ревью и при отладке. Claude Code CX Codex Cursor 13 278установок iii-sdk-reference iii-hq Справка по API iii SDK для Node.js, Python, Rust, Go и браузера. Помогает быстро найти правильный синтаксис регистрации воркеров, функций, триггеров, наблюдателей и каналов на нужном языке. Claude Code CX Codex Cursor +1 4 000установок iii-core-primitives iii-hq Справочник по базовым примитивам движка iii: регистрации функций, привязке триггеров, созданию воркеров и режимам вызова задач. Claude Code CX Codex Cursor +1 4 000установок iii-error-handling iii-hq Скилл учит агента распознавать коды ошибок iii-движка и SDK, различать сетевые сбои от отказов в доступе, определять, когда повторять вызов безопасно. Нужен, если пишешь код на Node, Python, Rust или в браузере с вызовами удалённых функций. Claude Code CX Codex Cursor +1 4 000установок mcp-builder официальный anthropics Скилл проводит через создание MCP-сервера на TypeScript или Python: от изучения протокола до тестов и оценки качества. Claude Code Claude.ai 130 949установок google-agents-cli-adk-code официальный Google Скилл даёт примеры и справку по Agent Development Kit: агентам, инструментам, колбэкам, состоянию и графовым workflow. Нужен при написании кода. Claude Code CX Codex Cursor +1 511 400установок lark-im larksuite Скилл подключает Lark IM к агенту: он отправляет сообщения, ищет историю, управляет чатами и файлами. Подойдёт для задач вокруг командных коммуникаций. Claude Code CX Codex Cursor +1 472 300установок

Вопросы о golang-spf13-viper

Как установить golang-spf13-viper в Claude Code?

Выполните команду npx skills add samber/cc-skills-golang --skill golang-spf13-viper -a claude-code в терминале проекта.

Что делает скилл golang-spf13-viper?

Он обучает ИИ-агента правилам работы с библиотекой spf13/viper, включая послойную загрузку настроек, работу с переменными окружения и связку с Cobra.

В какой момент нужно связывать флаги Cobra с Viper?

Привязку флагов через BindPFlag следует делать в init() или PersistentPreRunE. Если вызвать её в RunE, загрузка конфигурации отработает раньше и привязка не применится.

Исходный текст

SKILL.md · MIT
---
name: golang-spf13-viper
description: "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`."
user-invocable: true
license: MIT
compatibility: Designed for Claude Code, Codex or similar harness, and for projects using Golang.
metadata:
  author: samber
  version: "1.1.2"
  openclaw:
    emoji: "🔧"
    homepage: https://github.com/samber/cc-skills-golang
    requires:
      bins:
        - go
    install: []
    skill-library-version: "1.21.0"
allowed-tools: Read Edit Write Glob Grep Bash(go:*) Bash(golangci-lint:*) Bash(git:*) Agent WebFetch mcp__context7__resolve-library-id mcp__context7__query-docs Bash(godig:*) Bash(gopls:*) LSP mcp__gopls__*
paths:
  - "**/*.go"
---

**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:**

- [pkg.go.dev/github.com/spf13/viper](https://pkg.go.dev/github.com/spf13/viper)
- [github.com/spf13/viper](https://github.com/spf13/viper)

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.

```bash
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

```go
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](references/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:

```go
// ✓ 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](references/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):

```go
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](references/binding-and-env.md).

## Unmarshaling into structs

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

```go
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](references/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

```go
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](references/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:

```go
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](references/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

| Mistake | Why it fails | Fix |
| --- | --- | --- |
| `AutomaticEnv` without `SetEnvKeyReplacer` | `database.host` looks for `MYAPP_DATABASE.HOST` (dot preserved) — never matches | Add `SetEnvKeyReplacer(strings.NewReplacer(".", "_"))` before `AutomaticEnv` |
| No `mapstructure` tags on struct fields | Silently misses nested and underscore-named fields | Add `mapstructure:"key_name"` to every field |
| Using global viper in tests | State from one test contaminates the next, causing flaky ordering | Create `viper.New()` per test |
| Missing `ConfigFileNotFoundError` check | Missing config file crashes a service that should run on flags/env alone | `errors.As(err, &notFound)` — only propagate non-not-found errors |

## Further Reading

- [sources-and-formats.md](references/sources-and-formats.md) — supported file formats, multi-path search, MergeInConfig, remote KV (etcd/Consul)
- [binding-and-env.md](references/binding-and-env.md) — BindEnv, AutomaticEnv, SetEnvPrefix, SetEnvKeyReplacer, AllowEmptyEnv, timing rules
- [unmarshal.md](references/unmarshal.md) — Unmarshal, UnmarshalKey, mapstructure tags, custom DecodeHooks (Duration, IP, slice)
- [watch-and-reload.md](references/watch-and-reload.md) — WatchConfig, OnConfigChange, fsnotify caveats, atomic-rename trap, race-safe patterns
- [testing-and-isolation.md](references/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>.

© samber · MIT · samber/cc-skills-golang

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой