cobra

Cobra

Specific best practices and architectural patterns when working with Cobra.

Details

Language / Topic
goGo
Category
framework

Rules

balanced

Cobra

- Define root command in `cmd/root.go` with subcommands in separate files. Use `cobra.Command.RunE` (not `Run`) to return errors properly. Use `PersistentFlags()` on root for global flags and `Flags()` on subcommands for local flags.

Cobra

- Define root command in `cmd/root.go` with subcommands in separate files. Use `cobra.Command.RunE` (not `Run`) to return errors properly. Use `PersistentFlags()` on root for global flags and `Flags()` on subcommands for local flags.
- Use `cobra.MarkFlagRequired()` for mandatory flags. Bind flags to Viper config with `viper.BindPFlag()` for config file + flag + env var support. Use `cobra.ValidArgsFunction` for shell completion. Implement `PersistentPreRunE` on root for shared setup (config loading, logging). Use `cobra-cli` to scaffold new commands.