The cobra Package II
Let’s add commands to our cobra package.
We'll cover the following...
Adding command-line flags
We are going to create two global command-line flags and one command-line flag that is attached to a given command (two) and is not supported by the other two commands. Global command-line flags are defined in the ./cmd/root.go file. We are going to define two global flags named directory, which is a string, and depth, which is an unsigned integer.
Both global flags are defined in the init() function of ./cmd/root.go.
rootCmd.PersistentFlags().StringP("directory", "d", "/tmp", "Path to use.")rootCmd.PersistentFlags().Uint("depth", 2, "Depth of search.")viper.BindPFlag("directory", rootCmd.PersistentFlags().Lookup("directory"))viper.BindPFlag("depth", rootCmd.PersistentFlags().Lookup("depth"))
We use rootCmd.PersistentFlags() to define global flags followed by the data type of the flag. The name of the first flag is directory, and its shortcut is d, whereas the name of the second flag is depth and has no shortcut—if we want to add a shortcut to it, we should use the UintP() method instead. After defining the ...