Quick Start Guide
This guide will walk you through the most common use case for godotenv
: loading environment variables from a .env
file into a Go application.
Step 1: Create a .env
File
In the root directory of your project, create a new file named .env
. This file will store your configuration variables as key-value pairs.
File: .env
DB_HOST=localhost
DB_PORT=5432
DB_USER=myuser
DB_PASS=secret
API_KEY=a1b2c3d4e5f6
Security Note: The
.env
file often contains sensitive credentials. It's standard practice to add.env
to your.gitignore
file to prevent it from being committed to version control.
Step 2: Write Your Go Application
Next, create a main.go
file. We will use the godotenv
library to load the variables from .env
and then access them using the standard library's os.Getenv
function.
File: main.go
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
// godotenv.Load() will load variables from the .env file in the current directory
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
// Now you can access the variables using os.Getenv
dbHost := os.Getenv("DB_HOST")
dbPort := os.Getenv("DB_PORT")
apiKey := os.Getenv("API_KEY")
fmt.Println("Database Host:", dbHost)
fmt.Println("Database Port:", dbPort)
fmt.Println("API Key:", apiKey)
// The value for a non-existent key will be an empty string
nonExistent := os.Getenv("NON_EXISTENT_VAR")
fmt.Printf("Non-Existent Variable: '%s'\n", nonExistent)
}
Step 3: Run Your Application
Make sure you have the godotenv
library installed:
go get github.com/joho/godotenv
Now, run your application from the terminal:
go run main.go
Expected Output
You should see the values from your .env
file printed to the console:
Database Host: localhost
Database Port: 5432
API Key: a1b2c3d4e5f6
Non-Existent Variable: ''
That's it! You have successfully configured your Go application using a .env
file.