How do you assign a default value if an environment variable isn't set in Go?
In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass')
where pass
is the default value if MONGO_PASS
env var isn't set.
I tried an if statement based on os.Getenv
being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.
You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.
Or to assign default to VARIABLE at the same time: FOO="${VARIABLE:=default}" # If variable not set or null, set it to default.
The . env file contains the individual user environment variables that override the variables set in the /etc/environment file. You can customize your environment variables as desired by modifying your . env file.
There's no built-in to fall back to a default value, so you have to do a good old-fashioned if-else.
But you can always create a helper function to make that easier:
func getenv(key, fallback string) string { value := os.Getenv(key) if len(value) == 0 { return fallback } return value }
Note that as @michael-hausenblas pointed out in a comment, keep in mind that if the value of the environment variable is really empty, you will get the fallback value instead.
Even better as @ŁukaszWojciechowski pointed out, using os.LookupEnv
:
func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With