In Go, environment variables can be retrieved using os.Getenv, but it does not provide a built-in way to assign a default value if an environment variable is not set.
To achieve this functionality, you can create a helper function that checks for the emptiness of an environment variable and assigns a default value if needed:
func getenv(key, fallback string) string { value := os.Getenv(key) if len(value) == 0 { return fallback } return value }
This function accepts a key and a fallback value as arguments and returns the environment variable value if it exists, or the fallback value if the environment variable is unset.
For example, if you have an unset environment variable MONGO_PASS, you can assign it a default value of "pass" as follows:
mongoPassword := getenv("MONGO_PASS", "pass")
Alternatively, you can simplify the above approach using os.LookupEnv:
func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback }
This function is functionally equivalent to getenv but uses os.LookupEnv instead, which explicitly indicates whether an environment variable is set or not.
The above is the detailed content of How to Assign Default Values to Unset Go Environment Variables?. For more information, please follow other related articles on the PHP Chinese website!