Best Ways to Use Environment Variables in Golang

Sk Shahriar Ahmed Raka
2 min readAug 7, 2022

--

There are lots of ways to import Environment variable inside a golang project ,

godotenv is a Go (golang) port of the Ruby dotenv project (which loads `env` vars from a .env file).

In Golang, as far as i know there is two great package to read .env file easily , godotenv and viper , I prefer godotenv because it’s much easier .

Pros: Developers won’t see your production secrets. You can use different secrets in dev, test, and production, without having to modify the code.
Cons: Malicious code can read your secrets. The bulk of your application’s code is probably open-source libraries. Bad code may creep in without you knowing it.

Practical example for using godotenv

First run this command in terminal in that directory where your `main.go` file lives

go get github.com/joho/godotenv

In your .env file

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

In your `main.go` file

package main

import (
“github.com/joho/godotenv”
“log”
“os”
)

func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(“Error loading .env file”)
}

s3Bucket := os.Getenv(“S3_BUCKET”)
secretKey := os.Getenv(“SECRET_KEY”)

// now do something with s3 or whatever
}

There are a tons of ways you will find to use environment variable , but according to my little experience godotenv is the best option out there.

--

--

Sk Shahriar Ahmed Raka
Sk Shahriar Ahmed Raka

Written by Sk Shahriar Ahmed Raka

Software Engineer (Golang) | Specialized in Software Infrastructure, Security, and Penetration Testing | Proficient in CI/CD, Kubernetes, SvelteJS

Responses (1)