Cobra — Modern CLI Framework for Go Applications
Cobra is the most popular Go library for building command-line applications. It powers the CLI of Kubernetes (kubectl), GitHub CLI, Docker, Hugo, and hundreds of other tools — providing subcommands, flags, auto-generated help, and shell completions.
这个资产会安全暂存
这个资产会先安全暂存。复制的指令会要求 Agent 读取暂存文件,并在激活脚本、MCP 配置或全局配置前先确认。
npx -y tokrepo@latest install 0ffadd25-373d-11f1-9bc6-00163e2b0d79 --target codex先暂存文件;激活前需要读取暂存 README 和安装计划。
What it is
Cobra is a Go library for building command-line applications with subcommands, flags, auto-generated help text, and shell completions. It is the most widely used CLI framework in the Go ecosystem, powering the CLIs of Kubernetes (kubectl), GitHub CLI (gh), Docker, Hugo, and hundreds of other tools.
Cobra targets Go developers building CLI tools that need structured subcommands (like git commit, docker run, or kubectl apply). It handles argument parsing, validation, help generation, and man page creation.
How it saves time or tokens
Cobra eliminates the boilerplate of parsing flags, validating arguments, and generating help text. Its code generator scaffolds new commands with a single command. You focus on business logic while Cobra handles the CLI framework concerns.
Shell completion scripts (bash, zsh, fish, PowerShell) are auto-generated from your command definitions. Without Cobra, writing and maintaining completion scripts is a manual, error-prone process.
How to use
- Install Cobra and initialize a project:
go install github.com/spf13/cobra-cli@latest
cobra-cli init myapp
cd myapp
- Add a subcommand:
cobra-cli add serve
cobra-cli add migrate
- Implement the command logic in
cmd/serve.go:
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start the HTTP server",
Run: func(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetInt("port")
fmt.Printf("Starting server on port %d\n", port)
},
}
func init() {
serveCmd.Flags().IntP("port", "p", 8080, "Port to listen on")
rootCmd.AddCommand(serveCmd)
}
Example
A complete CLI with persistent flags and nested subcommands:
package main
import (
"fmt"
"github.com/spf13/cobra"
)
var verbose bool
var rootCmd = &cobra.Command{
Use: "myapp",
Short: "My application CLI",
}
var deployCmd = &cobra.Command{
Use: "deploy [environment]",
Short: "Deploy to an environment",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
fmt.Printf("Deploying to %s (verbose=%v)\n", args[0], verbose)
},
}
func main() {
rootCmd.PersistentFlags().BoolVarP(&verbose, "verbose", "v", false, "Verbose output")
rootCmd.AddCommand(deployCmd)
rootCmd.Execute()
}
Related on TokRepo
- AI tools for coding -- Development frameworks and libraries
- Automation tools -- CLI tools for automation workflows
Common pitfalls
- Putting all command logic in the Run function. Extract business logic into separate packages and keep commands thin. This makes the logic testable independently of the CLI framework.
- Overusing persistent flags. Persistent flags propagate to all subcommands. If a flag only applies to one command, make it a local flag to keep help text clean.
- Forgetting to call
cobra.CheckErr()on errors. Cobra provides consistent error handling. Use it instead oflog.Fatal()to get proper exit codes and error formatting.
常见问题
Cobra powers the CLIs of Kubernetes (kubectl), GitHub CLI (gh), Docker, Hugo, Helm, Terraform, and many other popular Go projects. It is the de facto standard for Go CLI development.
Both are popular Go CLI frameworks. Cobra is more opinionated with its code generator and file structure. urfave/cli is more lightweight and uses a functional style. Cobra has better shell completion support and is more widely adopted in large projects.
Yes. Cobra can auto-generate man pages, markdown documentation, and shell completion scripts from your command definitions. Run 'cobra-cli docs' or use the doc generation package programmatically.
Yes. Cobra and Viper (also by spf13) are designed to work together. Viper handles configuration files (YAML, JSON, TOML, env vars) and Cobra handles CLI flags. You can bind Cobra flags to Viper configuration keys for a unified config approach.
Cobra generates shell completion scripts automatically. Add a 'completion' command to your root command with 'rootCmd.AddCommand(completionCmd)'. Users then run 'myapp completion bash > /etc/bash_completion.d/myapp' to install completions.
引用来源 (3)
- Cobra GitHub— Cobra is the most popular Go library for building CLI applications
- Cobra User Guide— Cobra powers kubectl, GitHub CLI, Docker, and Hugo
- Cobra Completions Docs— Shell completion generation for CLI tools
讨论
相关资产
HTTPie CLI — Modern User-Friendly Command-Line HTTP Client
HTTPie is a modern, user-friendly command-line HTTP client for the API era. Intuitive syntax, formatted and colorized output, JSON support, sessions, authentication, file uploads, and plugins. The friendly alternative to curl for API exploration.
OpenAnt — Verified Vuln Pipeline CLI (Go + Python)
OpenAnt is a defensive vulnerability discovery CLI: it parses a repo, analyzes findings, and runs verification steps so security output is evidence-backed.
Augustus — LLM Vulnerability Scanner (Go CLI)
Augustus is a Go-based LLM vulnerability scanner covering 210+ adversarial attacks and 28 providers; verified 205★ and pushed 2026-05-11.
AIChat — All-in-One LLM CLI with 20+ Providers
AIChat is a CLI for 20+ LLM providers with shell assistant, RAG, agents, and function calling. 9.7K+ stars. MIT/Apache 2.0.