SKILL·F42446

go-cli

eduardo-sl
更新于 8 days ago
64
9
64
在 GitHub 上查看
apidesign

关于

This Claude Skill provides guidance for building robust command-line tools in Go, covering flag parsing, subcommands, proper I/O handling, and signal management. It helps developers decide when to use the standard library versus frameworks like Cobra/Viper. Use it specifically for CLI construction tasks, not for API design or project scaffolding.

快速安装

Claude Code

推荐
主要方式
npx skills add eduardo-sl/go-agent-skills -a claude-code
插件命令备选方式
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 克隆备选方式
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-cli

在 Claude Code 中复制并粘贴此命令以安装该技能

技能文档

Go CLI Design

A good CLI is a well-behaved Unix citizen: flags before magic, stdout for data, stderr for diagnostics, exit codes that scripts can trust, and Ctrl+C that actually stops it.

1. Structure: Testable main

func main() {
    ctx, stop := signal.NotifyContext(context.Background(),
        os.Interrupt, syscall.SIGTERM)
    defer stop()

    if err := run(ctx, os.Args[1:], os.Stdin, os.Stdout, os.Stderr); err != nil {
        fmt.Fprintln(os.Stderr, "error:", err)
        os.Exit(1)
    }
}

func run(ctx context.Context, args []string, stdin io.Reader, stdout, stderr io.Writer) error {
    fs := flag.NewFlagSet("mytool", flag.ContinueOnError)
    fs.SetOutput(stderr)
    verbose := fs.Bool("v", false, "verbose output")
    out := fs.String("o", "-", "output file (- for stdout)")
    if err := fs.Parse(args); err != nil {
        return err
    }
    // ...
    _ = verbose
    _ = out
    return nil
}
  • signal.NotifyContext makes Ctrl+C cancel the context — every long operation takes ctx and stops cleanly.
  • run receives args and streams — tests call it directly with strings.Reader/bytes.Buffer, no subprocess needed.
  • os.Exit only in main (it skips defers).

2. stdout vs stderr

  • stdout: the program's output — data, results, the thing you pipe.
  • stderr: logs, progress, warnings, usage errors.
  • --json or detecting a pipe (!term.IsTerminal(int(os.Stdout.Fd()))) should silence decorations, never change the data.
// ✅ Good — result to stdout, progress to stderr
fmt.Fprintf(stderr, "processed %d files\n", n)
fmt.Fprintln(stdout, result)

// ❌ Bad — mixing both into stdout breaks every pipe
fmt.Printf("processing...\ndone: %s\n", result)

3. Exit Codes

CodeMeaning
0Success
1Generic runtime failure
2Usage error (bad flags/arguments) — flag package's convention
>2Tool-specific, documented meanings (e.g. grep's 1 = no match)

Map errors to codes in one place (main), not scattered os.Exit calls. If scripts will branch on distinct failures, define sentinel errors and translate: errors.Is(err, ErrNoMatch) → 1.

4. Flags and Arguments

  • Flags for options, positional args for the primary operands: mytool -v convert input.yaml, not mytool --input=input.yaml.
  • Every flag has a usage string; -h/-help output is your primary UX.
  • Accept - as "stdin/stdout" for file arguments.
  • Defaults must be safe: destructive behavior behind explicit flags (--force), never default-on.
  • Read secrets from env or files, never from flags (ps leaks argv).

5. Subcommands

Standard library, fine up to a handful of commands:

switch fs.Arg(0) {
case "serve":
    return runServe(ctx, fs.Args()[1:], stdout, stderr)
case "migrate":
    return runMigrate(ctx, fs.Args()[1:], stdout, stderr)
default:
    fmt.Fprintln(stderr, usage)
    return fmt.Errorf("unknown command %q", fs.Arg(0))
}

Adopt Cobra when you need nested commands, generated help/completions, and many flags — the structure pays for the dependency:

var rootCmd = &cobra.Command{Use: "mytool", SilenceUsage: true}

var serveCmd = &cobra.Command{
    Use:   "serve",
    Short: "Start the server",
    RunE: func(cmd *cobra.Command, args []string) error {
        return serve(cmd.Context(), addr) // RunE returns errors; no os.Exit
    },
}

func init() {
    serveCmd.Flags().StringVar(&addr, "addr", ":8080", "listen address")
    rootCmd.AddCommand(serveCmd)
}

Cobra rules: always RunE (never Run + os.Exit), set SilenceUsage: true so runtime errors don't dump help, pass cmd.Context() down. Add Viper only when layered config (flags > env > file) is a real requirement — for most tools flag + os.Getenv is enough.

6. Output for Humans and Machines

  • --json flag for machine consumption; table/text default for humans.
  • Never emit ANSI colors when stdout is not a terminal or NO_COLOR is set.
  • Progress bars/spinners go to stderr and only when it's a terminal.

Verification Checklist

  1. run(ctx, args, stdin, stdout, stderr) pattern — logic testable without subprocess
  2. signal.NotifyContext wired; long operations respect ctx cancellation
  3. Data on stdout, diagnostics on stderr — verified by piping
  4. Exit codes: 0 success, 2 usage, documented codes otherwise; os.Exit only in main
  5. Every flag has usage text; -h output reviewed
  6. - accepted for stdin/stdout where files are taken
  7. Destructive actions require explicit flags
  8. No secrets via argv
  9. Cobra (if used): RunE everywhere, SilenceUsage, context propagated
  10. Colors/spinners disabled for non-TTY and NO_COLOR

GitHub 仓库

eduardo-sl/go-agent-skills
路径: skills/(architecture)/go-cli
0
FAQ

常见问题

什么是 go-cli Skill?

go-cli 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 Claude 无需额外提示即可执行与 go-cli 相关的任务。

如何安装 go-cli?

使用本页的安装命令:将 go-cli 作为插件添加到 Claude Code,或将其仓库克隆到 skills 目录,然后重启 Claude 以加载该 Skill。

go-cli 属于哪个分类?

go-cli 属于元分类。

go-cli 可以免费使用吗?

可以。go-cli 已收录在 AIMCP,可免费安装。

相关推荐技能

content-collections

Content Collections 是一个 TypeScript 优先的构建工具,可将本地 Markdown/MDX 文件转换为类型安全的数据集合。它专为构建博客、文档站和内容密集型 Vite+React 应用而设计,提供基于 Zod 的自动模式验证。该工具涵盖从 Vite 插件配置、MDX 编译到生产环境部署的完整工作流。

查看技能
polymarket

这个Claude Skill为开发者提供完整的Polymarket预测市场开发支持,涵盖API调用、交易执行和市场数据分析。关键特性包括实时WebSocket数据流,可监控实时交易、订单和市场动态。开发者可用它构建预测市场应用、实施交易策略并集成实时市场预测功能。

查看技能
creating-opencode-plugins

该Skill帮助开发者创建OpenCode插件,用于接入命令、文件、LSP等25+种事件。它提供了插件结构、事件API规范和JavaScript/TypeScript实现模式,适合需要拦截操作、扩展功能或自定义事件处理的场景。开发者可通过它快速构建响应式模块来增强OpenCode AI助手的能力。

查看技能
sglang

SGLang是一个专为LLM设计的高性能推理框架,特别适用于需要结构化输出的场景。它通过RadixAttention前缀缓存技术,在处理JSON、正则表达式、工具调用等具有重复前缀的复杂工作流时,能实现极速生成。如果你正在构建智能体或多轮对话系统,并追求远超vLLM的推理性能,SGLang是理想选择。

查看技能