dotenv

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2025 License: MIT Imports: 4 Imported by: 0

README

Dotenv

A lightweight Go package designed to simplify the configuration of your Go applications by loading environment variables from a .env file (or any file of your choice)

Note: The default env file is a ".env" file at the root of the project and the default logger writes to os.Stdout

Installation

go get -u github.com/tonievictor/dotenv

Usage

There are various ways to use this package.

  1. Using the default values for the filename and logger.
package main

import (
	"fmt"
	"os"

	"github.com/tonievictor/dotenv"
)

func main() {
    
    // loads the env variables using the defaults while ignoring the return values.
    dotenv.Config()

    envVariable := os.Getenv("MY_ENV_KEY")
    
    // This prints the value assigned to the MY_ENV_KEY
    fmt.Println(envVariable)
}
  1. You can also provide an env file and a logger.
package main

import (
	"fmt"
	"os"

	"github.com/tonievictor/dotenv"
)

func main() {
    filename := dotenv.WithFilename("env file")
    logger := log.New(os.Stdout, "Example logger", log.LstdFlags)

    dotenv.Config(filename, dotenv.WithLogger(logger))
    // you can also choose to provide just the filename or the logger
    // and use the default for the other.
    // dotenv.Config(filename)
    // or
    // dotenv.Config(dotenv.WithLogger(logger))

    envVariable := os.Getenv("MY_ENV_KEY")
    
    // This prints the value assigned to the MY_ENV_KEY
    fmt.Println(envVariable)
}

Note: dotenv.Config() returns a map of the environment variables and an error

Contributors

Tonie Victor - Author

Documentation

Overview

Package dotenv provides functionality for loading environment variables from a `.env` file and setting them as environment variables in the system. It supports reading key-value pairs from a file, skipping invalid or comment lines, and allows users to customize the filename and logger through options.

Example usage:

envVars, err := dotenv.Config(
  dotenv.WithFilename(".env"),
  dotenv.WithLogger(log.New(os.Stdout, "dotenv: ", log.LstdFlags)),
)
if err != nil {
  log.Fatal(err)
}
fmt.Println(envVars)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Config

func Config(params ...Option) (map[string]string, error)

Types

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithFilename

func WithFilename(f string) Option

func WithLogger

func WithLogger(l *log.Logger) Option

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL