Home  >  Article  >  Backend Development  >  How to Assign Default Values for Empty Environment Variables in Go?

How to Assign Default Values for Empty Environment Variables in Go?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-17 18:25:02989browse

How to Assign Default Values for Empty Environment Variables in Go?

Assigning Default Values for Empty Environment Variables in Go

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn