How to Assign Default Values to Unset Go Environment Variables?

DDD
Release: 2024-11-17 06:34:03
Original
586 people have browsed it

How to Assign Default Values to Unset Go Environment Variables?

Assigning Default Values to Unset Go Environment Variables

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template