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

Patricia Arquette
Release: 2024-11-17 18:25:02
Original
991 people have browsed it

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"
}
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template