This example Cobra app, https://github.com/kurtpeek/myCobraApp, contains a Cobra app scaffolded using the Cobra generator with the following commands:
cobra add serve
cobra add config
The directory structure is
.
├── LICENSE
├── cmd
│ ├── config.go
│ ├── root.go
│ └── serve.go
├── go.mod
├── go.sum
└── main.go
In config.go
, the string variable deviceUUID
is defined and bound to a flag for that command with a default value of "configDeviceUUID"
:
var deviceUUID string
func init() {
rootCmd.AddCommand(configCmd)
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
configCmd.Flags().StringVar(&deviceUUID, "deviceUUID", "configDeviceUUID", "Device UUID")
fmt.Println("deviceUUID after config init:", deviceUUID)
}
Similarly, in serve.go
the deviceUUID
variable is bound to a local flag:
func init() {
rootCmd.AddCommand(serveCmd)
serveCmd.Flags().StringVar(&deviceUUID, "deviceUUID", "serveDeviceUUID", "Device UUID")
fmt.Println("deviceUUID after serve init:", deviceUUID)
}
The problem is that if I run the config
command without specifying the deviceUUID
flag at the command line, it picks up the default value from the serve
command:
> go run main.go config
deviceUUID after config init: configDeviceUUID
deviceUUID after serve init: serveDeviceUUID
deviceUUID: serveDeviceUUID
config called
What seems to be happening is that the init()
functions in each file are run in alphabetical order, and the last one to run sets the default value for the flag.
How can I avoid this behavior? I would like the default value set in config.go
to always apply to the config
command. (I could, of course, declare separate variables like configDeviceUUID
and serveDeviceUUID
, but this seems a bit messy to me).