Home > Article > Backend Development > Golang Cobra multiple flags without value
I am new to golang and trying my first cli application using cobra framework.
My plan is to use few commands and use many flags. These flags do not have to have a value appended as they can simply be used with -r to reboot the device.
Currently, I have the following working, but I've been thinking, this isn't the right way to do it. So any help is greatly appreciated.
The current logic is that each command is appended with a default value and then I look for that value in the run command and trigger my function after capturing it.
My "working code" looks like below.
My init function contains the following content in the command.
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"
The running part is shown below.
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") } },
Perhaps to make the usage a little clearer, as mentioned in burak's comment - you can better differentiate between commands and flags. With cobra you can have a root command and subcommands attached to the root command. Additionally, each command can accept flags.
In your case, charger
is the root command and you need two subcommands: update_firmware
and reboot
.
As an example to restart the charger, you would execute the command:
$ charger reboot
In the code above you are trying to define the subcommand as a flag, which is possible but probably not a good practice.
Instead, the project should be set up as follows: https://github.com/hesamchobanlou/stackoverflow/tree/main/74934087
You can then move the updatefirmware(...)
action in the corresponding command definition under cmd/update_firmware.go instead of trying to check every flag variation on the root chargercmd.
If this doesn't help, please provide more details as to why you think your approach may not be correct?
The above is the detailed content of Golang Cobra multiple flags without value. For more information, please follow other related articles on the PHP Chinese website!