Introduction to GO Environment Variables
Environmental variables are dynamic key value pairs in an operating system. They are used to pass/convey configuration information to unix programs to enable programs to execute based on these environmental configurations. A good example is when an application has configurations for development, testing , staging and production environment.
In this article, we will learn about the OS package in Go, and explore ways to set, get, unset and lookup environmental variables. We will also learn how to load environment variables specific to our program to the os. These environmental variables required during development of software might be database connection strings and port, secret keys and many more.
Get environmental variables: os.Getenv()
The OS package provides the os.Getenv() method to get the environmental variables. This method is passed the key that you want to get the value for from the environmental variable list. Please note that , if the value of the provided key does not exist, nothing will be returned back.
Syntax
os.Getenv(KeyName)
Ensure that the os package
has been imported before making use of the methods provided by the os package. In the next example, we get some Go env variables and system environment variables.
Example
package main
import (
"fmt"
"os"
)
func main() {
SHELL := os.Getenv("SHELL")
GOPATH := os.Getenv("GOPATH")
fmt.Printf("SYSTEM SHELL %s \n", SHELL)
fmt.Printf("GOPATH %s \n", GOPATH)
}
Explanation
In the above example, we use the os.Getenv()
methods to get both Go environmental variables and system environment variables. The os.Getenv()
method returns a string type to the caller.
Output
$ go run main.go
SYSTEM SHELL /bin/bash
GOPATH /home/golinuxcloud/go
Set environmental variables: os.Setenv()
os.Setenv() used to set environment variables. This method takes two parameters namely the key and value.
Syntax
os.Setenv(key, value)
Example
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("PROD", "PRODUCTION")
PROD := os.Getenv("PROD")
fmt.Printf("Production environment: %s \n", PROD)
}
Explanation
In the above example, we set the environment variable by passing two strings to the os.Setenv()
method. The first parameter to the os.Setenv()
method is the key
and the second parameter is the value
. To test if the key has been set successfully, we get it using os.Getenv()
method and print the results to the terminal.
Output
$ go run main.go
Production environment: PRODUCTION
Delete/Unset environment variables: os.Unsetenv()
os.Unsetenv() method is responsible for deleting environment variables.
Syntax
os.Unsetenv(key)
Example
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("PROD", "PRODUCTION")
fmt.Printf("Production environment: %s \n", os.Getenv("PROD"))
os.Unsetenv("PROD")
fmt.Printf("Production environment: %s \n", os.Getenv("PROD"))
}
Explanation
In the above example, we first of all set an environment variable using os.Setenv(“PROD”, “PRODUCTION”)
. In the next line , we print the value of the PROD key.
This prints out the value of the environment variable. We later on unset the PROD key and print its value using. The value printed out is empty.
Output
$ go run main.go
Production environment: PRODUCTION
Production environment:
Look up environmental variables: os.LookupEnv()
The os.LookUpEnv() method checks if a key exists. It returns a value and a boolean. If the key is found the boolean value will be true else false.
Syntax
value, ok := os.LookupEnv(key)
Example
package main
import (
"fmt"
"os"
)
func main() {
value, ok := os.LookupEnv("GOPATH")
if !ok {
fmt.Printf("Value not found : %v \n", ok)
} else {
fmt.Printf("Value found : %s \n", value)
}
}
Output
$ go run main.go
Value found : /home/golinuxcloud/go
Get all environmental variables: os.Environ()
The os
package provides the os.Environ() method that returns a slice of all existing environmental variables.
Example
package main
import (
"fmt"
"os"
)
func main() {
for _, value := range os.Environ() {
fmt.Println(value)
}
}
Output
$ go run main.go
SHELL=/bin/bash
SESSION_MANAGER=local/golinuxcloud:@/tmp/.ICE-unix/2118,unix/golinuxcloud:/tmp/.ICE-unix/2118
QT_ACCESSIBILITY=1
COLORTERM=truecolor
XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg
SSH_AGENT_LAUNCHER=gnome-keyring
XDG_MENU_PREFIX=gnome-
TERM_PROGRAM_VERSION=1.71.1
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
APPLICATION_INSIGHTS_NO_DIAGNOSTIC_CHANNEL=true
LC_ADDRESS=sw_KE
GoDotEnv Package
Up to this point we have been setting environment variables using the os.Setenv(
) method. In real world applications, it's not safe to hard code our environment variables. For example, API keys can not be hard coded into our application, and they can not be pushed in our code repositories like github or bitbucket. The solution for this is to add our application environment variables in a .env
file. The .env
file stores environment variables so that our application can load.
There are several packages that can be used to load environment variables from a file like github.com/joho/
godotenv
and github.com/spf13/viper.
In This article, we will use the dotenv
package to load environment variables.
In your root folder using your terminal enter the following commands.
$ touch main.go
$ touch .env
$ go mod init example.com/env
$ go get github.com/joho/godotenv
The first two commands create two files main.g
o and .env
. The third command (go mod init example.com/env
)creates a module. The go get
github.com/joho/godotenv
installs the godotenv
package into our module.
.env file
HOST=postgres-movie-app
PASSWORD=topsecret
DBNAME=developer
PORT=5432
main.go file
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func getEnvVar(key string) string {
err := godotenv.Load(".env")
if err != nil {
log.Fatal(err)
}
return os.Getenv(key)
}
func main() {
fmt.Printf("HOST %s \n", getEnvVar("HOST"))
fmt.Printf("PASSWORD %s \n", getEnvVar("PASSWORD"))
fmt.Printf("DBNAME %s \n", getEnvVar("DBNAME"))
fmt.Printf("PORT %s \n", getEnvVar("PORT"))
}
Explanation
In the above example, we use the godotenv package to load postgres db configurations to our system. We have defined a function with a single responsibility of getting environment variables from the .env
file.
Output
go run main.go
HOST postgres-movie-app
PASSWORD topsecret
DBNAME developer
PORT 5432
Summary
During development of Go applications, we usually require to set and get environment variables so that our applications can run as expected. We therefore use environment variables as a universal mechanism for conveying configuration information. In this article , we have used the os package to get, set, unset, lookupEnv environment variables. We have also learnt how to load sensitive information to our application using the godotenv package.
References
https://gobyexample.com/environment-variables
https://pkg.go.dev/os#Getenv
What's Next
Golang Global Variables Explained [Beginners Tutorial]
3 ways to read file into variable in Golang [SOLVED]