Unlike Python, Go does not provide a built-in mechanism to assign default values to unset environment variables. To achieve this functionality, you can employ a traditional if-else statement:
if value := os.Getenv("MONGO_PASS"); value == "" { value = "pass" }
However, to simplify the process, you can create a helper function:
func getenv(key, fallback string) string { value := os.Getenv(key) if len(value) == 0 { return fallback } return value }
This function takes two parameters: the key of the environment variable and the default value to be returned if the variable is empty.
It is important to note that if the environment variable is explicitly set to an empty string, the helper function will return the fallback value.
Alternatively, you can leverage the os.LookupEnv function:
func getEnv(key, fallback string) string { if value, ok := os.LookupEnv(key); ok { return value } return fallback }
This approach uses the os.LookupEnv function to check the existence of the environment variable. If it exists, it returns its value; otherwise, it returns the provided fallback value.
The above is the detailed content of How to Assign Default Values for Empty Environment Variables in Go?. For more information, please follow other related articles on the PHP Chinese website!