Skip to content

Instantly share code, notes, and snippets.

@mrsimonemms
Created April 26, 2025 11:31
Show Gist options
  • Save mrsimonemms/f66e65a9c8be3544be8a66b67e5c1c5a to your computer and use it in GitHub Desktop.
Save mrsimonemms/f66e65a9c8be3544be8a66b67e5c1c5a to your computer and use it in GitHub Desktop.
Golang Cobra Bind Env
// Bind an environment variable to a Cobra CLI argument
func bindEnv(key string, defaultValue ...any) {
envvarName := strings.Replace(key, "-", "_", -1)
envvarName = strings.ToUpper(envvarName)
err := viper.BindEnv(key, envvarName)
cobra.CheckErr(err)
for _, val := range defaultValue {
viper.SetDefault(key, val)
}
}
func init() {
rootCmd.AddCommand(runCmd)
// This will look for an envvar called SOME_KEY and give a default value of "some-value"
bindEnv("some-key", "some-value")
rootCmd.Flags().StringP("some-key", "k", viper.GetString("some-key"), "This is some value set as a Cobra argument")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment