I am using the github.com/spf13/cobra
package to interpret process' command-line arguments, and I'm having difficulty understanding how parameter values are determined.
I have a working program (below) which uses internal variables that get updated with parameter values:
OptPort := 8088
rootCmd := &cobra.Command{
Use: "server",
Short: "Root command short version",
Long: "Root command long version",
}
startCmd := &cobra.Command{
Use: "start",
Short: "Start command short version",
Long: "Start command long version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("args: " + strings.Join(args, " "))
fmt.Println("port: " + OptPort)
},
}
startCmd.Flags().IntVarP(&OptPort, "port", "p", OptPort, "Port to listen to")
rootCmd.AddCommand(startCmd)
rootCmd.Execute()
The output I get is as follows:
args:
port: 8088
I realize that I can get the port value by interrogating the port variable, but I would have thought the values would be in the args variable also. Is the args variable empty because I am doing something wrong? If the args variable is expected to be empty, what is the purpose of the args variable?
The args
variable is for extra parameters that are passed into that particular cobra
verb. For example, if you wanted your start
verb on the server
command to (for example) require a particular configuration file, you could simply pass that in like
server start -p 8080 config.yml
and "config.yml"
is placed in args[0]
.