Created
April 26, 2025 11:31
-
-
Save mrsimonemms/f66e65a9c8be3544be8a66b67e5c1c5a to your computer and use it in GitHub Desktop.
Golang Cobra Bind Env
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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