godotenv

repository·main·Indexed 27 days ago

https://github.com/joho/godotenv

A Go port of the Ruby dotenv project that loads environment variables from .env files into the process environment. It provides a library for loading, overloading, and parsing environment data, an autoload package for automatic integration, and a CLI tool to run commands with environment variables loaded from files.

Tokens
1.7K
Snippets
4
Records
15
Agent score
92%

What's inside godotenv

  1. Use the godotenv autoload package

    main

    For the simplest integration, you can import the autoload package. This will automatically read and load the .env file into your environment upon import, requiring no additional function calls.

    import _ "github.com/joho/godotenv/autoload"
  2. Manage multiple environments (Precedence & Conventions)

    main

    Existing environment variables take precedence over variables loaded via godotenv.Load().

    A common convention for managing environments (development, test, production) is to use an environment variable like {YOURAPP}_ENV to determine which file to load.

    To force overwriting existing environment variables, use godotenv.Overload().

    env := os.Getenv("FOO_ENV")
    if "" == env {
      env = "development"
    }
    
    godotenv.Load() // The Original .env
    godotenv.Load(".env." + env)
    if "test" != env {
      godotenv.Load(".env.local")
    }
    godotenv.Load(".env." + env + ".local")
  3. Install godotenv

    main

    Depending on your use case, you can install godotenv as a library, a tool dependency, or a standalone binary command.

    As a library

    Use this to import the package into your Go application code.

    As a tool dependency

    Requires Go >= 1.24.

    As a bin command

    Install it to your $GOPATH/bin to use the godotenv CLI tool.

  4. Load environment variables from custom files or sources

    main
    You can specify custom filenames or multiple files to godotenv.Load(). Additionally, you can parse environment data without modifying the process environment by using Read(), Parse(), Unmarshal(), or Parse() with different input types.
  5. Load environment variables from a .env file

    main

    Use godotenv.Load() to read a .env file from the current working directory and inject its contents into the process's environment variables (os.Getenv).

    By default, it only loads variables if they do not already exist in the environment. To overwrite existing variables, use godotenv.Overload() instead.

    package main
    
    import (
        "log"
        "os"
    
        "github.com/joho/godotenv"
    )
    
    func main() {
      err := godotenv.Load()
      if err != nil {
        log.Fatal("Error loading .env file")
      }
    
      s3Bucket := os.Getenv("S3_BUCKET")
      secretKey := os.Getenv("SECRET_KEY")
    }
  6. Write environment variables to a file or string

    main

    You can convert a map of strings into a formatted .env file or a string using Write() and Marshal().

    // Write a map to a file
    env, err := godotenv.Unmarshal("KEY=value")
    err := godotenv.Write(env, "./.env")
    
    // Marshal a map to a string
    env, err := godotenv.Unmarshal("KEY=value")
    content, err := godotenv.Marshal(env)
  7. Use the godotenv CLI command

    main

    If installed as a binary, you can use the godotenv command to run other commands with environment variables loaded from a file.

    • -f <path>: Specify the path to the .env file. If omitted, it defaults to .env in the current working directory.
    • -o: Overwrite existing environment variables (default behavior is to not override).
  8. Load environment variables into the process with Load()

    main

    Use Load() to read environment files and inject their key-value pairs into the current process's environment variables.

    • If no arguments are provided, it defaults to loading a .env file in the current directory.
    • You can specify multiple filenames to load sequentially.
    • Important: Load() will NOT override an environment variable that already exists in the process. It is best used for setting development defaults.

    Call this function as early as possible in your program, ideally in main().

  9. Execute a command with loaded environment variables using Exec()

    main

    Use Exec() to load environment variables from specified files and then immediately run an external command. This function automatically connects the command's Stdin, Stdout, and Stderr to the current process.

    Arguments:

    • filenames []string: Files to load (defaults to .env if empty).
    • cmd string: The command to run.
    • cmdArgs []string: The arguments for the command.
    • overload bool: If true, uses Overload() (overwrites existing vars); if false, uses Load() (does not overwrite).
  10. Read environment variables into a map with Read()

    main

    Use Read() to parse environment files and return the key-value pairs as a map[string]string instead of writing them to the process environment.

    • If no arguments are provided, it defaults to reading .env in the current directory.
    • It follows the same file loading semantics as Load() (sequential loading from provided filenames).
  11. Parse environment data from strings or bytes

    main

    If you have environment data in memory rather than in files, use the following functions to convert them into a map[string]string:

    • Unmarshal(str string): Parses a string.
    • UnmarshalBytes(src []byte): Parses a byte slice.
    • Parse(r io.Reader): Parses data from any io.Reader.
  12. Serialize environment maps to files with Write() and Marshal()

    main

    To save environment variables back to a file:

    • Marshal(envMap map[string]string): Converts a map into a dotenv-formatted string. Keys are sorted alphabetically. Values are backslash-escaped and wrapped in double quotes, unless the value is an integer.
    • Write(envMap map[string]string, filename string): Serializes the map and writes it directly to the specified file.