Parsing environment variables with Go is simple, thanks to the standard library os
package.
os.Getenv()
gets an environment variable. It’s not possible to determine not set or empty. Use os.LookupEnv()
to be able to do that.
name := os.Getenv("NAME")
os.Setenv()
sets an environment variable.
os.Setenv("NAME", "Flavio")
os.Unsetenv()
unsets an environment variable.
os.Unsetenv("NAME")
os.Clearenv()
unsets all environment variables.
os.Clearenv()
os.Environ()
returns a slice of strings containing all the environment variables in key=value
format.
vars := os.Environ()
os.ExpandEnv()
given a string, expands $VAR environment variables entries to the corresponding value.
s := os.ExpandEnv("$NAME is italian")
os.LookupEnv()
returns the value of the environment variable in its first parameter if set, otherwise the second parameter is false. Allows to distinguish unset from empty value.
name, ok := os.LookupEnv("NAME")
More go tutorials:
- Using Shell Pipes with Go
- Implement Events Listeners in Go through Channels
- The basics of a Go Web Server
- Go Date and Time Formatting
- JSON processing with Go
- Accessing HTTP POST parameters in Go
- Generating random numbers and strings in Go
- Go, convert a string to a bytes slice
- Solving the "does not support indexing" error in a Go program