Cobra CLI With Flag Precedence

Build a CLI with Cobra supporting flags subcommands and config precedence.

GoCli Tooling

Code

gosnippet
18 lines
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

FAQ

Does this require external packages?
Yes — `github.com/spf13/cobra`. Add it to your project before running the snippet.