Building Powerful CLI Tools in Go with Cobra π
Introduction If you've ever used kubectl, hugo, gh (GitHub CLI), or helm, you've already used a CLI built with Cobra. It's the standard library for building command-line interfaces in Go β and for ...

Source: DEV Community
Introduction If you've ever used kubectl, hugo, gh (GitHub CLI), or helm, you've already used a CLI built with Cobra. It's the standard library for building command-line interfaces in Go β and for good reason. In this blog, we'll walk through everything you need to know about Cobra π β from installing it and creating your first command, all the way to subcommands, flags, argument validation and lifecycle hooks. Plenty of examples along the way. Installation & Project Setup π οΈ Step 1: Install Cobra # Add cobra to your Go module go get github.com/spf13/cobra@latest Step 2: (Optional) Install cobra-cli generator The cobra-cli tool generates command boilerplate so you don't have to write it from scratch every time go install github.com/spf13/cobra-cli@latest Step 3: Recommended project structure Keep your CLI commands organized β one file per command inside cmd/: myapp/ βββ main.go β tiny entry point βββ cmd/ β βββ root.go β rootCmd lives here β βββ serve.go β "serve" subcommand β ββ