douyan1244 2016-08-02 21:41
浏览 353
已采纳

使用github.com/spf13/cobra获取参数值

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?

  • 写回答

1条回答 默认 最新

  • dqnrk44682 2016-08-04 15:48
    关注

    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].

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?