How to Use Environment Variables in Golang From .env Files

Robin
Updated on June 28, 2023

Environment variables are key-value pairs that are set in an operating system's environment. You can use them to store configuration information, such as database connection strings, API keys, file paths, or other values required by an application.

The os package provides various built-in methods to interact with the operating system and access the environment variables in Golang directly from the system.

When you use environment variables to store and get sensitive information like database connection strings or API keys in your Golang applications, it makes your applications more secure and portable.

In Golang, it's easy to manage environment variables. You can set new environment variables for your application, get the values and delete existing ones.

You also have the option to load your environment variables from .env files in Go. In this way, you can set multiple variables at the same time without doing it individually.

How to Set Environment Variables in Golang

To set environment variables in Golang, you can use the os.Setenv function from the os package.

This is the syntax:

          os.Setenv(key,value) 
        

This Setenv() function accept 2 arguments: key for the environment variable and the value.

          package main

import (
	"fmt"
	"os"
)

func main() {
	// Set environment variable
	os.Setenv("API_KEY", "f5adb47-5671-4cc6-bb0b-648cfd177d17")

}
        

In this example, I am storing API key in the environment variable named "API_KEY" with the value. We can get this value inside our application using the key.

Also Read: Golang Variable: Different Ways to Create Variables in Golang


How to Get Environment Variables in Golang

You can access environment variables using the os package. This package has os.Getenv() function that takes a key and returns the value for that key.

          package main

import (
	"fmt"
	"os"
)

func main() {
	// Set environment variable
	os.Setenv("API_KEY", "f5adb47-5671-4cc6-bb0b-648cfd177d17")

	// Get the value of the environment variable
	value := os.Getenv("API_KEY")

	fmt.Printf("Value: %s\n", value)
}
        

I am calling the os.Getenv() function with the key "API_KEY" to get its value. If you provide any key that doesn't exist, it will return an empty string.

This function returns the value of a single environment variable. But if you want, you can get all the environment variables at once.

          package main

import (
	"fmt"
	"os"
)

func main() {
	// Set environment variable
	os.Setenv("API_KEY", "f5adb47-5671-4cc6-bb0b-648cfd177d17")

	// Get all the environment variables
	values := os.Environ()

	fmt.Printf("Values: %s\n", values)
}
        

The os.Environ() function returns all the environment variables from your system in the form of "key=value" as a slice of the string, including the variables you set in your Golang application.

Also Read: Mastering Constant in Golang: Declare and Use It Like a Pro


Check If an Environment Variable is Available or Not

To check if an environment variable is available in Go, you can use the os.LookupEnv() function. This will help you to confirm that the value is available before using it.

          package main

import (
	"fmt"
	"os"
)

func main() {
	// Set environment variable
	os.Setenv("API_KEY", "f5adb47-5671-4cc6-bb0b-648cfd177d17")

	// Check If an Environment Variable is Available or Not
	value, ok := os.LookupEnv("API_KEY")

	if ok {
		fmt.Printf("Values: %v\n", value)
	} else {
		fmt.Println("Environment Variable is not available")
	}
}
        

When you call this function with a key, it returns two values: the value of the environment variable and a boolean indicating whether the variable exists or not. Let's assign these values to the variables value and ok respectively.

Inside the if statement, we check the value of ok. If it is true, it means the environment variable exists, and you can use the value of this environment variable.

If ok is false, it means the environment variable does not exist. In that case, the value variable contains an empty string.

Also Read: Deep Dive into Variable Scopes in Golang: Learn with Examples


Delete Environment Variables in Golang

To delete an environment variable in Golang, you can use the os.Unsetenv() function from the os package. You have to call this function with a key that you want to delete.

          package main

import (
	"fmt"
	"os"
)

func main() {
	// Set environment variable
	os.Setenv("API_KEY", "f5adb47-5671-4cc6-bb0b-648cfd177d17")

	// Detele environment variable
	err := os.Unsetenv("API_KEY")

	if err != nil {
		fmt.Println("Error deleting environment variable:", err)
	} else {
		fmt.Println("Environment variable deleted successfully.")
	}
}
        

I am calling the os.Unsetenv() function with the "API_KEY" key. This function will remove the specified environment variable from the environment.

The os.Unsetenv function returns an error if there was a problem deleting the environment variable. You can check if there is an error and display different messages.

          os.Clearenv()
        

You can also delete all the environment variables at once by calling the os.Clearenv() function from the os package.

Don't execute this function in your home computer. Because it will end up deleting all of your environment variables from your computer.

Also Read: Understanding All Data Types in Golang: A Complete Guide


Load Environment Variables From .env Files in Go

Loading environment variables from .env files is better than loading them individually. It will help you to separate your environment variables from your application code.

When you share your code with other developers or push it to a version control like Git, you can remove the .env file and no one will know your sensitive information.

To load environment variables from a .env file in Go, you can use a third-party package like "godotenv". It will read the file and set variables to your system.

Run the following command in your terminal to install the package:

          go get github.com/joho/godotenv
        

Suppose you have a .env file in your project directory with the following environment variables in the format "KEY=VALUE".

          API_KEY=abc123
DB_HOST=localhost
DB_PORT=5432
        

The "godotenv" package has a load() function to load environment variables from a .env file.

          package main

import (
	"fmt"
	"log"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	// Load environment variables from .env file
	err := godotenv.Load()

	if err != nil {
		log.Fatal("Error loading .env file:", err)
	}

	// Access the loaded environment variables
	apiKey := os.Getenv("API_KEY")
	dbHost := os.Getenv("DB_HOST")
	dbPort := os.Getenv("DB_PORT")

	// Use the environment variables in your code
	fmt.Println("API Key:", apiKey)
	fmt.Println("Database Host:", dbHost)
	fmt.Println("Database Port:", dbPort)
}
        

When you execute this function, it also returns an error if there's an error loading the file. You can handle it by logging a fatal error.

Finally, you can access those environment variables inside your code using the os.Getenv() function.

What will happen if you name your .env file differently?

          err := godotenv.Load(".env.dev")
        

By default, godotenv.Load() function reads the .env file automatically from your project directory. But if you have your file differently like .evn.dev in your project, you have to specify the name while calling the godotenv.Load() function.

Also Read: Type Aliases in Golang: Create Custom Names For Your Types


Conclusion

Using environment variables brings several benefits, including enhanced configuration management, increased portability, improved security, flexibility, and separation of concerns.

Golang makes it easy to handle environment variables by providing various functions in the os package. You can set new variables manually, get the values and delete a specific environment variable from the system.

By using the "godotenv" package, you are able to effortlessly load environment variables from a .env file into our Go application. This enables easy configuration changes without the need to modify and redeploy the code.

Related Posts