drmq16019 2017-11-06 05:31
浏览 27
已采纳

没有参数匹配的golang眼镜蛇子命令

i want to create golang CLI with cobra. For now, it runs well. I have created something like foobar create --username johndoe. But I need subcommands like foobar create user --username johndoe. There is user subcommand.

I have created with arguments matching,

var applicationCmd = &cobra.Command{
   Use:   "application",
   Short: "Create/Read/Update application",
   Long: `You can create any user or partner.`,
   Run: (cmd *cobra.Command, args []string) {
        if len(args) < 1 {
            fmt.Printf("%sPlease choose any object that you want to change e.g (user, partner)%s
", chalk.Red, chalk.Reset)
        }
        if stringUtil.Contains(args, "user") {
            createUser()
        }
        if stringUtil.Contains(args, "partner") {
            createPartner()
        }
   },
}

but I think there is a better way to do it using cobra rather than using arguments matching like this. Any suggestion?

  • 写回答

2条回答 默认 最新

  • doupeng8494 2017-11-10 16:29
    关注

    I've solved this. Just add new cobra command to applicationCmd like so

    applicationCmd.AddCommand(yourNewCommand)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?