How to assign default value if env var is empty?

There’s no built-in to fall back to a default value,
so you have to do a good old-fashioned if-else.

But you can always create a helper function to make that easier:

func getenv(key, fallback string) string {
    value := os.Getenv(key)
    if len(value) == 0 {
        return fallback
    }
    return value
}

Note that as @michael-hausenblas pointed out in a comment,
keep in mind that if the value of the environment variable is really empty, you will get the fallback value instead.

Even better as @ƁukaszWojciechowski pointed out, using os.LookupEnv:

func getEnv(key, fallback string) string {
    if value, ok := os.LookupEnv(key); ok {
        return value
    }
    return fallback
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)