How to add a .env file in a GO language project

Credit goes to the 👉 Original Post 👈👌👍💛

Why should we use the environment variable?

Suppose you have an application with many features and each feature needs to access the Database. You configured all the DB information like DBURLDBNAMEUSERNAME and PASSWORD in each feature.

There are a few major disadvantages to this approach, there can be many.

Security Issue:

  • You’re entering all the information in the code. Now, all the unauthorized person also have access to the DB.
  • If you’re using code versioning tool like git then the details of your DB will go public once you push the code.

Code Management:

  • If you are changing a single variable then you have to change in all the features. There is a high possibility that you’ll miss one or two. 😌 been there
  • You can categorize the environment variables like PRODDEV, or TEST. Just prefix the variable with the environment.

At the start, it might look like some extra work, but this will reward you a lot in your project.

⚠️ Just don’t forget to include your environment files in the .gitignore.

It is time for some action. 🔨

What are we going to do in this tutorial?

In this tutorial, we will access environment variables in 3 different ways.

You can use according to your requirement.

  • os package
  • godotenv package
  • viper package

Create a Project

Create a project go-env-ways outside the $GOPATH.

Initialize the module

Open the terminal inside the project root directory, and run the below command.

go mod init go-env-ways

This module will keep a record of all the packages and their version used in the project. It is similar to package.json in nodejs.

Let’s start with the easiest one, using os package.

os Package

Golang provides os package, an easy way to configure and access the environment variable.

To set the environment variable,

os.Setenv(key, value)

To get the environment variable,

value := os.Getenv(key)

Create a new file main.go inside the project.

package main

import (
"fmt"
"os"
)

// use os package to get the env variable which is already set
func envVariable(key string) string {

// set env variable using os package
os.Setenv(key, "gopher")

// return the env variable using os package
return os.Getenv(key)
}

func main() {
// os package
value := envVariable("name")

fmt.Printf("os package: name = %s \n", value)
fmt.Printf("environment = %s \n", os.Getenv("APP_ENV"))
}

Run the below command to check.

APP_ENV=prod go run main.go

// Output
os package: name = gopher
environment = prod

GoDotEnv Package

The easiest way to load the .env file is using godotenv package.

Install

Open the terminal in the project root directory.

go get github.com/joho/godotenv

godotenv provides a Load method to load the env files.

// Load the .env file in the current directory
godotenv.Load()

// or

godotenv.Load(".env")

Load method can load multiple env files at once. This also supports yaml. For more information check out the documentation.

Create a new .env file in the project root directory.

STRONGEST_AVENGER=Thor

Update the main.go.

package main

import (

...
// Import godotenv
"github.com/joho/godotenv"
)


// use godot package to load/read the .env file and
// return the value of the key
func goDotEnvVariable(key string) string {

// load .env file
err := godotenv.Load(".env")

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

return os.Getenv(key)
}

func main() {
// os package
...

// godotenv package
dotenv := goDotEnvVariable("STRONGEST_AVENGER")

fmt.Printf("godotenv : %s = %s \n", "STRONGEST_AVENGER", dotenv)
}

Open the terminal and run the main.go.

go run main.go

Comments