gogo-cobra

Golang Cobra subcommands without arguments matching


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\n", 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?


Solution

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

    applicationCmd.AddCommand(yourNewCommand)