GoDotEnv: An Overview

GoDotEnv is a Go port of the popular Ruby dotenv library. Its primary purpose is to load environment variables from a .env file into your application's environment, making it easier to manage configuration across different deployment environments.

The Twelve-Factor App Philosophy

Storing configuration in the environment is a core tenet of a twelve-factor app. Application settings that change between deployments—such as database credentials, API keys for external services, or deployment-specific flags—should be separated from the code. Environment variables are the ideal way to manage this.

However, setting environment variables on development machines or in continuous integration (CI) environments can be cumbersome, especially when managing multiple projects. godotenv solves this problem by allowing you to define these variables in a simple .env text file.

Key Features

  • Simple Integration: Load your entire environment configuration with a single line of code.
  • Flexible File Loading: Load the default .env file, or specify one or more custom file paths.
  • Environment-Aware: By default, godotenv will not override environment variables that are already set, allowing production environments to take precedence.
  • Versatile Parsing: Parse .env files from local files, io.Reader streams, or even plain strings.
  • CLI Tool: Use godotenv as a command-line utility to run programs with a specific environment loaded.
  • File Generation: Programmatically generate valid .env files from a map of key-value pairs.

A Simple Example

Create a .env file in your project root:

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

In your Go application, load the file:

package main

import (
    "log"
    "os"

    "github.com/joho/godotenv"
)

func main() {
  // Load environment variables from .env file
  err := godotenv.Load()
  if err != nil {
    log.Fatal("Error loading .env file")
  }

  // Access your variables
  s3Bucket := os.Getenv("S3_BUCKET")
  secretKey := os.Getenv("SECRET_KEY")

  log.Printf("S3 Bucket: %s", s3Bucket)
  log.Printf("Secret Key: %s", secretKey)
}

This documentation will guide you through installation, basic usage, advanced features, and the specifics of the .env file format.