Cobra CLI With Flag Precedence
Build a CLI with Cobra supporting flags subcommands and config precedence.
Code
package main
import ("github.com/spf13/cobra";"fmt")
var rootCmd = &cobra.Command{
Use: "app",
Short: "A CLI application",
}
var serveCmd = &cobra.Command{
Use: "serve",
Run: func(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetInt("port")
fmt.Printf("Serving on port %d\n", port)
},
}
func init() {
serveCmd.Flags().IntP("port", "p", 8080, "Port number")
rootCmd.AddCommand(serveCmd)
}
func main() { rootCmd.Execute() }How it works
Cobra CLI With Flag Precedence keeps everything in the functions init and main.
What to watch for
- External dependency:
github.com/spf13/cobra— install it before running the snippet.
Using it
The main signature is written as func init()
The demo output is labeled (Serving on port), so the output doubles as a step-by-step trace of what the file did.
Key statements
func main() { rootCmd.Execute() }
func init() {
serveCmd.Flags().IntP("port", "p", 8080, "Port number")
rootCmd.AddCommand(serveCmd)
}
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- Does this require external packages?
- Yes — `github.com/spf13/cobra`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.