Best Way to Use Environment Variables in Golang

Best Way to Use Environment Variables in Golang

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 environment variables 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 beacuse 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 exparience godotenv is the best option out there.