Environment variables are set in the Operating System(OS) and can be accessed and operated using the operating system’s command-line interface or API. In most cases, environment variables are set using the export
or set
command, followed by the name and value of the environment variable.
Golang environment variables
Golang environment variables are global variables set outside of the program and can be accessed by the program at runtime. Environment variables store configuration settings, such as database connection strings, API keys, and other sensitive information that should not be hardcoded into the program.
To access environment variables in Golang, use the os.Getenv() function.
Golang os getenv
Golang os.getenv() is a built-in function that can retrieve an environment variable’s value. It takes the environment variable’s name as an argument and returns its value as a string. The function returns an empty string if the specified variable does not exist.
Syntax
func Getenv(key string) string
Parameters
It takes a key as an argument which is a string.
Return value
It returns the value based on the provided key. It returns an empty value if the variable is not present.
Example
Here is an example of how to use the os.Getenv()
function.
package main
import (
"fmt"
"os"
)
func main() {
current_user := os.Getenv("USER")
fmt.Println("The current user is:", current_user)
// Retrieve the value of the "SHELL" environment variable
shell := os.Getenv("SHELL")
fmt.Println("The current shell is:", shell)
}
Output
The current user is: krunallathiya
The current shell is: /bin/zsh
In this example, the os.Getenv() function fetches the values of the USER and SHELL environment variables, which are then printed to the console using the fmt.Println() function.
Conclusion
Environment variables are robust for storing configuration settings and sensitive information in Golang. By using the os.Getenv() function, you can access the environment variables.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.