Assigning Default Values for Nil Environment Variables in Go
In Go, unlike Python's os.getenv() function, there is no built-in mechanism to assign a default value if an environment variable is not set. To address this issue, the following approaches can be employed:
Option 1: Using an if-else Block
Although relying on if-else statements to check variable states is generally discouraged, it can be used to assign default values for environment variables:
var mongoPassword string if mongoPass := os.Getenv("MONGO_PASS"); mongoPass != "" { mongoPassword = mongoPass } else { mongoPassword = "pass" }
Option 2: Creating a Helper Function
For multiple environment variables, creating a helper function provides a cleaner approach:
func getenv(key, fallback string) string { value := os.Getenv(key) if len(value) == 0 { return fallback } return value }
To use it:
mongoPassword := getenv("MONGO_PASS", "pass")
Option 3: Using os.LookupEnv(key) Boolean
os.LookupEnv returns two values: the value and its existence status. This can be used to set a default value as follows:
func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback }
Note that if the environment variable's value is empty, the fallback value will be assigned instead.
The above is the detailed content of How to Assign Default Values for Nil Environment Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!