121

How do you assign a default value if an environment variable isn't set in Go?

In Python I could do mongo_password = os.getenv('MONGO_PASS', 'pass') where pass is the default value if MONGO_PASS env var isn't set.

I tried an if statement based on os.Getenv being empty, but that doesn't seem to work due to the scope of variable assignment within an if statement. And I'm checking for multiple env var's, so I can't act on this information within the if statement.

4
  • 4
    An if does work.
    – Volker
    Oct 30, 2016 at 9:02
  • 1
    @Volker it does? I tried it with ``` mpass := os.Getenv("MONGO_PASS") if len(mpass) == 0 { log.Println("MONGO_PASS env var not set, using mongo default") mpass := "pass" }``` And I get this: ./server.go:63: mpass declared and not used
    – Ryan Clair
    Oct 30, 2016 at 17:43
  • Where line 63 aligns with mpass variable within the if block (I use mpass later on).
    – Ryan Clair
    Oct 30, 2016 at 17:57
  • Figured it out. Should have been using = instead of := on the mpass within the if statement. Thanks for calling me out Volker :-)
    – Ryan Clair
    Oct 30, 2016 at 18:54

8 Answers 8

179

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
}
2
  • 3
    Note that while above code is correct, you should be aware of the semantics: since it tests for length of the string value and the empty string "" has length 0 it means that when the env variable is set to "" you would get the fallback/default value rather than the value (which is trivially ""). Really depends on your use case but I thought it's worth pointing out since I once ran into this semantic error and burnt a few cycles debugging it ;) Oct 30, 2016 at 18:48
  • 28
    Instead of Getenv you could use LookupEnv. It also returns ok boolean status that the value was indeed there. Feb 23, 2017 at 7:06
54

What you're looking for is os.LookupEnv combined with an if statement.

Here is janos's answer updated to use LookupEnv:

func getEnv(key, fallback string) string {
    value, exists := os.LookupEnv(key)
    if !exists {
        value = fallback
    }
    return value
}
24

Go doesn't have the exact same functionality as Python here; the most idiomatic way to do it though, I can think of, is:

mongo_password := "pass"
if mp := os.Getenv("MONGO_PASS"); mp != "" {
    mongo_password = mp
}
3
  • Thank you for the suggestion Michael. I tried exactly that, which was similar to my initial attempt, and it complains that mongo_password inside of the if block isn't used (same error as my comment to Volker above. I thought this had sometime to do with the fact that variables within an if block were limited to that block, and couldn't get outside? Or am I mistaken, and that's declared variables... and my error is due to how I'm using the variable?
    – Ryan Clair
    Oct 30, 2016 at 18:12
  • 1
    Note that the line mongo_password := "pass" is essential, because with this mongo_password is declared and defined (set to pass as the default value). If you don't have that line then I can imagine an error. In our case above, only mp has the local scope of the if, FWIW. Oct 30, 2016 at 18:42
  • 1
    OHHHHHH. Light f'ing bulb. Thank you. I was mixing up declare (:=) and assignment (=). Works like a champ. You rock Michael.
    – Ryan Clair
    Oct 30, 2016 at 18:53
20

To have a clean code I do this:

myVar := getEnv("MONGO_PASS", "default-pass")

I defined a function that is used in the whole app

// getEnv get key environment variable if exist otherwise return defalutValue
func getEnv(key, defaultValue string) string {
    value := os.Getenv(key)
    if len(value) == 0 {
        return defaultValue
    }
    return value
}
3

Had the same question as the OP and found someone encapsulated the answers from this thread into a nifty library that is fairly simple to use, hope this help others!

https://github.com/caarlos0/env

0
2

For more complex application you can use tooling such as viper, which allows you to set global custom default values, parse configuration files, set a prefix for your app's env var keys (to ensure consistency and name spacing of env var configurations) and many other cool features.

Sample code:

package main

import (
    "fmt"

    "github.com/spf13/viper"
)

func main() {
    viper.AutomaticEnv() // read value ENV variable
    // Set default value
    viper.SetEnvPrefix("app")
    viper.SetDefault("linetoken", "DefaultLineTokenValue")

    // Declare var
    linetoken := viper.GetString("linetoken")

    fmt.Println("---------- Example ----------")
    fmt.Println("linetoken :", linetoken)
}
1
  • While this is a cooler and proper way for PROD app, it might be overkill for a simple/trivial app
    – Akshay
    Apr 21, 2022 at 15:01
2

I also had the same problem and I just created a small package called getenvs exactly to answer this problem.

Getenvs supports string, bool, int and float and it can be used like below:

package main

import (
    "fmt"

    "gitlab.com/avarf/getenvs"
)

func main() {
    value := getenvs.GetEnvString("STRING_GETENV", "default-string-value")
    bvalue, _ := getenvs.GetEnvBool("BOOL_GETENV", false)
    ivalue, _ := getenvs.GetEnvInt("INT_GETENV", 10)

    fmt.Println(value)
    fmt.Println(bvalue)
    fmt.Println(ivalue)
}
1

In case you are OK with adding little dependency you can use something like https://github.com/urfave/cli

package main

import (
  "os"

  "github.com/urfave/cli"
)

func main() {
  app := cli.NewApp()

  app.Flags = []cli.Flag {
    cli.StringFlag{
      Name: "lang, l",
      Value: "english",
      Usage: "language for the greeting",
      EnvVar: "APP_LANG",
    },
  }

  app.Run(os.Args)
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.