← 返回 Skills 市场
samber

Golang Cli

作者 Samuel Berthe · GitHub ↗ · v1.1.2 · MIT-0
cross-platform ✓ 安全检测通过
192
总下载
0
收藏
0
当前安装
3
版本数
在 OpenClaw 中安装
/install golang-cli
功能描述
Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration...
使用说明 (SKILL.md)

Persona: You are a Go CLI engineer. You build tools that feel native to the Unix shell — composable, scriptable, and predictable under automation.

Modes:

  • Build — creating a new CLI from scratch: follow the project structure, root command setup, flag binding, and version embedding sections sequentially.
  • Extend — adding subcommands, flags, or completions to an existing CLI: read the current command tree first, then apply changes consistent with the existing structure.
  • Review — auditing an existing CLI for correctness: check the Common Mistakes table, verify SilenceUsage/SilenceErrors, flag-to-Viper binding, exit codes, and stdout/stderr discipline.

Go CLI Best Practices

Use Cobra + Viper as the default stack for Go CLI applications. Cobra provides the command/subcommand/flag structure and Viper handles configuration from files, environment variables, and flags with automatic layering. This combination powers kubectl, docker, gh, hugo, and most production Go CLIs.

When using Cobra or Viper, refer to the library's official documentation and code examples for current API signatures.

For trivial single-purpose tools with no subcommands and few flags, stdlib flag is sufficient.

Quick Reference

Concern Package / Tool
Commands & flags github.com/spf13/cobra
Configuration github.com/spf13/viper
Flag parsing github.com/spf13/pflag (via Cobra)
Colored output github.com/fatih/color
Table output github.com/olekukonko/tablewriter
Interactive prompts github.com/charmbracelet/bubbletea
Version injection go build -ldflags
Distribution goreleaser

Project Structure

Organize CLI commands in cmd/myapp/ with one file per command. Keep main.go minimal — it only calls Execute().

myapp/
├── cmd/
│   └── myapp/
│       ├── main.go              # package main, only calls Execute()
│       ├── root.go              # Root command + Viper init
│       ├── serve.go             # "serve" subcommand
│       ├── migrate.go           # "migrate" subcommand
│       └── version.go           # "version" subcommand
├── go.mod
└── go.sum

main.go should be minimal — see assets/examples/main.go.

Root Command Setup

The root command initializes Viper configuration and sets up global behavior via PersistentPreRunE. See assets/examples/root.go.

Key points:

  • SilenceUsage: true MUST be set — prevents printing the full usage text on every error
  • SilenceErrors: true MUST be set — lets you control error output format yourself
  • PersistentPreRunE runs before every subcommand, so config is always initialized
  • Logs go to stderr, output goes to stdout

Subcommands

Add subcommands by creating separate files in cmd/myapp/ and registering them in init(). See assets/examples/serve.go for a complete subcommand example including command groups.

Flags

See assets/examples/flags.go for all flag patterns:

Persistent vs Local

  • Persistent flags are inherited by all subcommands (e.g., --config)
  • Local flags only apply to the command they're defined on (e.g., --port)

Required Flags

Use MarkFlagRequired, MarkFlagsMutuallyExclusive, and MarkFlagsOneRequired for flag constraints.

Flag Validation with RegisterFlagCompletionFunc

Provide completion suggestions for flag values.

Always Bind Flags to Viper

This ensures viper.GetInt("port") returns the flag value, env var MYAPP_PORT, or config file value — whichever has highest precedence.

Argument Validation

Cobra provides built-in validators for positional arguments. See assets/examples/args.go for both built-in and custom validation examples.

Validator Description
cobra.NoArgs Fails if any args provided
cobra.ExactArgs(n) Requires exactly n args
cobra.MinimumNArgs(n) Requires at least n args
cobra.MaximumNArgs(n) Allows at most n args
cobra.RangeArgs(min, max) Requires between min and max
cobra.ExactValidArgs(n) Exactly n args, must be in ValidArgs

Configuration with Viper

Viper resolves configuration values in this order (highest to lowest precedence):

  1. CLI flags (explicit user input)
  2. Environment variables (deployment config)
  3. Config file (persistent settings)
  4. Defaults (set in code)

See assets/examples/config.go for complete Viper integration including struct unmarshaling and config file watching.

Example Config File (.myapp.yaml)

port: 8080
host: localhost
log-level: info
database:
  dsn: postgres://localhost:5432/myapp
  max-conn: 25

With the setup above, these are all equivalent:

  • Flag: --port 9090
  • Env var: MYAPP_PORT=9090
  • Config file: port: 9090

Version and Build Info

Version SHOULD be embedded at compile time using ldflags. See assets/examples/version.go for the version command and build instructions.

Exit Codes

Exit codes MUST follow Unix conventions:

Code Meaning When to Use
0 Success Operation completed normally
1 General error Runtime failure
2 Usage error Invalid flags or arguments
64-78 BSD sysexits Specific error categories
126 Cannot execute Permission denied
127 Command not found Missing dependency
128+N Signal N Terminated by signal (e.g., 130 = SIGINT)

See assets/examples/exit_codes.go for a pattern mapping errors to exit codes.

I/O Patterns

See assets/examples/output.go for all I/O patterns:

  • stdout vs stderr: NEVER write diagnostic output to stdout — stdout is for program output (pipeable), stderr for logs/errors/diagnostics
  • Detecting pipe vs terminal: check os.ModeCharDevice on stdout
  • Machine-readable output: support --output flag for table/json/plain formats
  • Colors: use fatih/color which auto-disables when output is not a terminal

Signal Handling

Signal handling MUST use signal.NotifyContext to propagate cancellation through context. See assets/examples/signal.go for graceful HTTP server shutdown.

Shell Completions

Cobra generates completions for bash, zsh, fish, and PowerShell automatically. See assets/examples/completion.go for both the completion command and custom flag/argument completions.

Testing CLI Commands

Test commands by executing them programmatically and capturing output. See assets/examples/cli_test.go.

Use cmd.OutOrStdout() and cmd.ErrOrStderr() in commands (instead of os.Stdout / os.Stderr) so output can be captured in tests.

Common Mistakes

Mistake Fix
Writing to os.Stdout directly Tests can't capture output. Use cmd.OutOrStdout() which tests can redirect to a buffer
Calling os.Exit() inside RunE Cobra's error handling, deferred functions, and cleanup code never run. Return an error, let main() decide
Not binding flags to Viper Flags won't be configurable via env/config. Call viper.BindPFlag for every configurable flag
Missing viper.SetEnvPrefix PORT collides with other tools. Use a prefix (MYAPP_PORT) to namespace env vars
Logging to stdout Unix pipes chain stdout — logs corrupt the data stream for the next program. Logs go to stderr
Printing usage on every error Full help text on every error is noise. Set SilenceUsage: true, save full usage for --help
Config file required Users without a config file get a crash. Ignore viper.ConfigFileNotFoundError — config should be optional
Not using PersistentPreRunE Config initialization must happen before any subcommand. Use root's PersistentPreRunE
Hardcoded version string Version gets out of sync with tags. Inject via ldflags at build time from git tags
Not supporting --output format Scripts can't parse human-readable output. Add JSON/table/plain for machine consumption

Related Skills

See samber/cc-skills-golang@golang-project-layout, samber/cc-skills-golang@golang-dependency-injection, samber/cc-skills-golang@golang-testing, samber/cc-skills-golang@golang-design-patterns skills.

安全使用建议
This skill appears coherent and appropriate for helping build or review Go CLI apps. Before using examples in production: (1) review any example code you copy-paste (especially config init that uses viper.AutomaticEnv()) so it doesn't unintentionally bind or expose environment variables from your environment; (2) note examples read $HOME and look for config files — ensure paths and permissions are acceptable for your use; (3) the skill can be invoked by the agent (normal behavior) and may run allowed tools (git, go, linters) if the agent has those permissions — only enable it for agents you trust.
功能分析
Type: OpenClaw Skill Name: golang-cli Version: 1.1.2 The golang-cli skill bundle is a comprehensive and idiomatic guide for developing Go CLI applications using industry-standard libraries like Cobra and Viper. It provides well-structured examples for configuration layering, signal handling, and Unix-compliant I/O patterns across files like assets/examples/config.go and assets/examples/output.go. No evidence of malicious intent, data exfiltration, or harmful prompt injection was found; the requested tool permissions (e.g., Bash for go/git) are strictly aligned with its stated purpose of Go development.
能力评估
Purpose & Capability
Name/description match the content: SKILL.md is Go CLI best-practices and the bundle contains many example Cobra/Viper source files. The only required binary is 'go', which is appropriate.
Instruction Scope
SKILL.md focuses on building/reviewing Go CLIs and the examples show config, env, file watching, signal handling, exit codes, completion, etc. This is in-scope. One noteworthy behavior: examples use viper.AutomaticEnv() and read $HOME for config files — expected for CLI config guidance but it means code examples will bind environment variables automatically if used verbatim, so reviewers should be aware of that side effect.
Install Mechanism
Instruction-only skill with no install spec and no downloads; lowest install risk.
Credentials
The skill declares no required environment variables or credentials. The SKILL.md recommends Viper for env config (including AutomaticEnv) which is reasonable for the described purpose but may cause inadvertent env var binding if example code is used without review.
Persistence & Privilege
always:false and no config paths/credential access. The skill allows normal autonomous invocation (disable-model-invocation:false), which is the platform default — not a concern here by itself.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install golang-cli
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /golang-cli 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.1.2
- Bumped version to 1.1.2. - Updated metadata version in SKILL.md. - Fixed typo in the Quick Reference table: now lists the correct package for table output (`olekukonko/tablewriter`). - Added a new evals/evals.json file.
v1.1.1
- Removed the sample evaluation file: evals/evals.json - No changes to documentation or features; this is a minor cleanup release.
v1.1.0
golang-cli 1.1.0 - Expanded to cover best practices for Go CLI development, including command structure, flag handling, config layering, version embedding, exit codes, I/O, and testing. - Explicit recommendations for using Cobra + Viper, with quick-reference tables and project structure example. - Detailed sections for root command setup, subcommands, flags (persistent/local, validation, completion), argument validation, and configuration resolution order. - Guidance on version/build info via ldflags, exit code standards, stdout/stderr discipline, signal handling with contexts, and auto-generated shell completion. - Suitable for use when building, modifying, or reviewing any Go CLI—especially with cobra, viper, or urfave/cli.
元数据
Slug golang-cli
版本 1.1.2
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 3
常见问题

Golang Cli 是什么?

Golang CLI application development. Use when building, modifying, or reviewing a Go CLI tool — especially for command structure, flag handling, configuration... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 192 次。

如何安装 Golang Cli?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install golang-cli」即可一键安装,无需额外配置。

Golang Cli 是免费的吗?

是的,Golang Cli 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Golang Cli 支持哪些平台?

Golang Cli 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Golang Cli?

由 Samuel Berthe(@samber)开发并维护,当前版本 v1.1.2。

💬 留言讨论