How to Use .env Files in Go with godotenv

Load .env files in Go by installing godotenv, calling godotenv.Load(), and accessing variables with os.Getenv().

Install the godotenv library, load the .env file in your main function, and access variables via os.Getenv.

  1. Install the library by running go get github.com/joho/godotenv.
  2. Import the package and load the file in your main function using godotenv.Load().
  3. Retrieve your environment variable using os.Getenv("VARIABLE_NAME").
package main

import (
	"fmt"
	"os"

	"github.com/joho/godotenv"
)

func main() {
	godotenv.Load()
	fmt.Println(os.Getenv("MY_VAR"))
}