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.
- Install the library by running
go get github.com/joho/godotenv.
- Import the package and load the file in your
main function using godotenv.Load().
- 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"))
}
Using .env files in Go with godotenv lets your program read settings from a simple text file instead of hardcoding them. It works like a configuration file that your computer reads before your program starts, keeping secrets like passwords out of your code. You use this when you need to change settings for different environments like testing or production without rewriting your code.