A lightweight, zero-dependency Go package for loading environment variables from .env and .env.local files into your application.
- File Priority: Automatically loads
.envand overrides with.env.localif present. - Shell Support: Recognizes the
exportkeyword. - Comment Handling: Ignores lines starting with
#and strips inline comments. - Smart Quoting: Automatically handles values wrapped in single (
') or double (") quotes. - Zero Dependencies: Uses only the Go standard library.
go get github.com/rickferrdev/dotenv
.env
PORT=8080
DB_URL="postgres://user:password@localhost:5432/db"
# This is a comment
DEBUG=true
.env.local
PORT=3000 # Overrides the value in .env
Call dotenv.Collect() as early as possible in your main function (or in an init function) to populate os.Environ.
package main
import (
"fmt"
"os"
"github.com/rickferrdev/dotenv"
)
func main() {
// Load variables from .env and .env.local
dotenv.Collect()
port := os.Getenv("PORT")
fmt.Printf("Server starting on port: %s\n", port)
}Collect(): Iterates throughFilenameVariables(defaulting to.envand.env.local). It parses each line, strips theexportprefix if it exists, and ignores comments.quotes(): A helper function that ensures values likeKEY="value"orKEY='value'are stored simply asvalue, while also cleaning up trailing inline comments.
You can override the files the package looks for by modifying the FilenameVariables slice before calling Collect:
dotenv.FilenameVariables = []string{".env.production", ".env"}
dotenv.Collect()