Use environment variables in Go

With the help of the standard library, it is very simple to use Go to parse environment variablesospackage.

os.Getenv() getEnvironment variables. Unable to determine whether it is not set or empty. useos.LookupEnv()Able to do this.

name := os.Getenv("NAME")

os.Setenv() setEnvironment variables.

os.Setenv("NAME", "Flavio")

os.Unsetenv() Not setEnvironment variables.


os.Clearenv() cancel all of themEnvironment variables.


os.Environ()Return asheetA string containing all environment variableskey=valueformat.

vars := os.Environ()

os.ExpandEnv()Give a string,Expand $VAREnter the environment variable item to the corresponding value.

s := os.ExpandEnv("$NAME is italian")

os.LookupEnv()If set, the value of the environment variable is returned in its first parameter, otherwise the second parameter is false. Allows to distinguish between unset values and empty values.

name, ok := os.LookupEnv("NAME")

More tutorials: