gogo-cobra

Golang Cobra multiple flags with no value


I'm new to Golang, and i'm trying out my first CLI application, using the Cobra framework.

My plan is to have few commands, with many flags. These flags, don't have to have a value attached to them, since they can simply be -r to restart the device.

Currently, i have the following working, but i keep thinking, that this cannot be the correct way to do it. So any help is appreciated.

The logic is currently, that each command, get's a default value attached to it, and then i look for this, in the run command, and triggers my function, once it captures it.

My "working code" looks like below.

My init function, in the command contains the following.

chargerCmd.Flags().StringP("UpdateFirmware", "u", "", "Updeates the firmware of the charger")
    chargerCmd.Flags().Lookup("UpdateFirmware").NoOptDefVal = "yes"
    chargerCmd.Flags().StringP("reboot", "r", "", "Reboots the charger")
    chargerCmd.Flags().Lookup("reboot").NoOptDefVal = "yes"

And the run section looks like this.

Run: func(cmd *cobra.Command, args []string) {
        input, _ := cmd.Flags().GetString("UpdateFirmware")
        if input == "yes" {
            fmt.Println("Updating firmware")
            UpdateFirmware(os.Getenv("Test"), os.Getenv("Test2")) 
        }
        input, _ = cmd.Flags().GetString("reboot")
        if input == "yes" {
            fmt.Println("Rebooting Charger")
        }
    },

Solution

  • Maybe to make the usage a bit cleaner, as stated in the comment from Burak - you can better differentiate between commands and flags. With cobra you have the root command and sub-commands attached to the root command. Additionaly each command can accept flags.

    In your case, charger is the root commands and you want two sub-commands: update_firmware and reboot.

    So as an example to reboot the charger, you would execute the command:

    $ charger reboot
    

    In the code above, you are trying to define sub-commands as flags, which is possible, but likely not good practice.

    Instead, the project should be set-up something like this: https://github.com/hesamchobanlou/stackoverflow/tree/main/74934087

    You can then move the UpdateFirmware(...) operation within the respective command definition under cmd/update_firmware.go instead of trying to check each flag variation on the root chargerCmd.

    If that does not help, provide some more details on why you think your approach might not be correct?