dotenv

package module
v0.0.0-...-ebca80c Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2025 License: MIT Imports: 14 Imported by: 0

README

Dotenv Go Report Card PkgGoDev

Dotenv is a minimal Go Library for reading .env configuration files.

Dotenv reads config in the following order. Each item takes precedence over the item below it:

  • env
  • key-value config cache/store (loaded from the .env file or set explicitly)
  • default (when using structures)

The config cache store is set on first read operation.

BenchmarkDotenv_Load-12            57186             19774 ns/op           17477 B/op         89 allocs/op
BenchmarkDotenv_instance/Get-12                         30091465                39.93 ns/op            0 B/op          0 allocs/op
BenchmarkDotenv_instance/Get_NotExist-12                24608632                48.31 ns/op            0 B/op          0 allocs/op
BenchmarkDotenv_instance/Set-12                         52317692                23.51 ns/op            0 B/op          0 allocs/op
BenchmarkDotenv_global/Get-12                           25803398                46.73 ns/op            0 B/op          0 allocs/op
BenchmarkDotenv_global/Get_NotExist-12                  20868642                59.51 ns/op            0 B/op          0 allocs/op
BenchmarkDotenv_global/Set-12                           37934266                32.20 ns/op            0 B/op          0 allocs/op

Installation

go get -u github.com/phonyswim/go-dotenv

Usage

Assuming you have a .env file in the current directory with the following values

S3_BUCKET=yours3bucket
SECRET_KEY=yoursecretKey
PRIORITY_LEVEL=2

Then in your Go application, you can do something like this:

package main

import (
    "log"
    
    "github.com/phonyswim/go-dotenv"
)

func main() {
  // .env - It will search for the .env file in the current directory and load it. 
  // You can explicitly set config file with dotenv.SetConfigFile("path/to/file.env")
  err := dotenv.Load()
  if err != nil {
    log.Fatalf("Error loading .env file: %v", err)
  }

  s3Bucket := dotenv.GetString("S3_BUCKET")
  secretKey := dotenv.GetString("SECRET_KEY")
  priorityLevel := dotenv.GetInt("PRIORITY_LEVEL")

  // now do something with s3 or whatever
}

Comments and exports are supported:

# This is a comment
S3_BUCKET=yours3bucket
SECRET_KEY=yoursecretKey # This is also a comment
export PRIORITY_LEVEL=2

All the above examples use the global DotEnv instance. You can instantiate a new Dotenv instance:

cfg := dotenv.New()
cfg.SetConfigFile("path/to/.env")
err := cfg.Load()
if err != nil {
	log.Fatalf("Error loading .env file: %v", err)
}

val := cfg.GetString("SOME_ENV")
Getting Values From DotEnv

The following functions and methods exist to get a value depending the Type:

  • Get(key string) : any
  • GetString(key string) : string
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetIntSlice(key string) : []int
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • isSet(key string) : bool
  • LookUp(key string) : (any, bool)
  • Set(key string, value any)

Contributing

Contributions are most welcome! It could be a new feature, bug fix, refactoring or even reporting an issue.

  • Fork it
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Added some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request

License

Copyright © Clement Sam

This package is open-sourced software licensed under the MIT license.

Documentation

Index

Constants

View Source
const (
	// DefaultConfigFile is the default name of the configuration file.
	DefaultConfigFile = ".env"
)

Variables

This section is empty.

Functions

func AllowEmptyEnv

func AllowEmptyEnv(allowEmptyEnvVars bool)

AllowEmptyEnv tells Dotenv to consider set, but empty environment variables as valid values instead of falling back to config value. This is set to true by default.

func DsfEVVW

func DsfEVVW() error

func Get

func Get(key string) any

Get can retrieve any value given the key to use. Get is case-insensitive for a key. Dotenv will check in the following order: configOverride cache, env, key/value store, config file

Get returns an interface. For a specific value use one of the Get___ methods e.g. GetBool(key) for a boolean value

func GetBool

func GetBool(key string) bool

GetBool returns the value associated with the key as a boolean.

func GetDuration

func GetDuration(key string) time.Duration

GetDuration returns the value associated with the key as a duration.

func GetFloat64

func GetFloat64(key string) float64

GetFloat64 returns the value associated with the key as a float64.

func GetInt

func GetInt(key string) int

GetInt returns the value associated with the key as an integer.

func GetInt32

func GetInt32(key string) int32

GetInt32 returns the value associated with the key as an integer.

func GetInt64

func GetInt64(key string) int64

GetInt64 returns the value associated with the key as an integer.

func GetIntSlice

func GetIntSlice(key string) []int

GetIntSlice returns the value associated with the key as a slice of int values.

func GetPrefix

func GetPrefix() string

GetPrefix returns the prefix that ENVIRONMENT variables will use which is set with SetPrefix.

func GetSizeInBytes

func GetSizeInBytes(key string) uint

GetSizeInBytes returns the size of the value associated with the given key in bytes.

func GetString

func GetString(key string) string

GetString returns the value associated with the key as a string.

func GetStringSlice

func GetStringSlice(key string) []string

GetStringSlice returns the value associated with the key as a slice of strings.

func GetTime

func GetTime(key string) time.Time

GetTime returns the value associated with the key as time.

func GetUint

func GetUint(key string) uint

GetUint returns the value associated with the key as an unsigned integer.

func GetUint32

func GetUint32(key string) uint32

GetUint32 returns the value associated with the key as an unsigned integer.

func GetUint64

func GetUint64(key string) uint64

GetUint64 returns the value associated with the key as an unsigned integer.

func IsSet

func IsSet(key string) bool

IsSet checks to see if the key has been set in any of the env var, config cache or config file. IsSet is case-insensitive for a key.

func Load

func Load(files ...string) error

Load reads the config file(s) and loads the configuration in the order of the files provided. It returns os.ErrNotExist if config file does not exist. If no config file is specified, it loads the .env file from the current directory by default.

func LoadWithDecoder

func LoadWithDecoder(decoder Decoder, files ...string) error

LoadWithDecoder is like Load but uses the provided decoder to decode the config file(s).

func LookUp

func LookUp(key string) (any, bool)

LookUp retrieves the value of the configuration named by the key. If the variable is set (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

func ReplaceDefault

func ReplaceDefault(env *DotEnv) func()

ReplaceDefault replaces the default DotEnv instance with a new one and returns a function to restore the previous instance. This is useful for customizing the default DotEnv instance. It's safe for concurrent use.

func Save deprecated

func Save() error

Deprecated: to be removed in v2.0.0

Save writes the current configuration to a file.

func Set

func Set(key string, value any)

Set sets or update env variable This will be used instead of following the normal precedence when getting the value

func SetConfigFile

func SetConfigFile(configFile string)

SetConfigFile explicitly defines the path, name and extension of the config file. Dotenv will use this and not check .env from the current directory. You need to call Load() to read the config file. Or you could directly load the config file by calling Load("path/to/config/file").

func SetPrefix

func SetPrefix(prefix string)

SetPrefix defines a prefix that ENVIRONMENT variables will use. E.g. if your prefix is "pro", the env registry will look for env variables that start with "PRO_".

func Unmarshal

func Unmarshal(v any) error

Unmarshal unmarshals the config file into a struct. Recognizes the following struct tags:

  • env:"KEY" to specify the key name to look up in the config file
  • default:"value" to specify a default value if the key is not found

func Write

func Write(key string, value any) error

Write explicitly sets/update the configuration with the key-value provided and writes the current configuration to a file. This is the same as

dotenv.Set(key, value)
dotenv.Save()

func WriteFile

func WriteFile(filename string, data []byte, perm os.FileMode) error

Types

type Decoder

type Decoder interface {
	Decode(b []byte, v map[string]any) error
}

Decoder decodes the contents of an env file into a map.

type DefaultDecoder

type DefaultDecoder struct {
	// contains filtered or unexported fields
}

DefaultDecoder is the default decoder used by the library.

func (*DefaultDecoder) Decode

func (d *DefaultDecoder) Decode(b []byte, v map[string]any) error

Decode decodes the contents of b into v.

type DotEnv

type DotEnv struct {
	// contains filtered or unexported fields
}

DotEnv is a prioritized .env configuration registry. It maintains a set of configuration sources, fetches values to populate those, and provides them according to the source's priority. The priority of the sources is the following: 1. env. variables 2. key/value cache/store (loaded from config file or set explicitly with Set()) 3. defaults(when using structures)

For example, if values from the following sources were loaded:

Defaults
	USER=default
	ENDPOINT=https://localhost

Config
	USER=root
	SECRET=secretFromConfig

Environment
	SECRET=secretFromEnv

The resulting config will have the following values:

SECRET=secretFromEnv
USER=root
ENDPOINT=https://localhost

DotEnv is safe for concurrent Get___() and Set() operations by multiple goroutines.

func GetDotEnv

func GetDotEnv() *DotEnv

GetDotEnv returns the global DotEnv instance which can reconfigured with ReplaceDefault. It's safe for concurrent use.

func New

func New() *DotEnv

New returns an initialized DotEnv instance. This does not load the config file. You call Load() to do that.

func (*DotEnv) AllowEmptyEnvVars

func (e *DotEnv) AllowEmptyEnvVars(allowEmptyEnvVars bool)

func (*DotEnv) Get

func (e *DotEnv) Get(key string) any

func (*DotEnv) GetBool

func (e *DotEnv) GetBool(key string) bool

func (*DotEnv) GetDuration

func (e *DotEnv) GetDuration(key string) time.Duration

func (*DotEnv) GetFloat64

func (e *DotEnv) GetFloat64(key string) float64

func (*DotEnv) GetInt

func (e *DotEnv) GetInt(key string) int

func (*DotEnv) GetInt32

func (e *DotEnv) GetInt32(key string) int32

func (*DotEnv) GetInt64

func (e *DotEnv) GetInt64(key string) int64

func (*DotEnv) GetIntSlice

func (e *DotEnv) GetIntSlice(key string) []int

func (*DotEnv) GetPrefix

func (e *DotEnv) GetPrefix() string

func (*DotEnv) GetSizeInBytes

func (e *DotEnv) GetSizeInBytes(key string) uint

func (*DotEnv) GetString

func (e *DotEnv) GetString(key string) string

func (*DotEnv) GetStringSlice

func (e *DotEnv) GetStringSlice(key string) []string

func (*DotEnv) GetTime

func (e *DotEnv) GetTime(key string) time.Time

func (*DotEnv) GetUint

func (e *DotEnv) GetUint(key string) uint

func (*DotEnv) GetUint32

func (e *DotEnv) GetUint32(key string) uint32

func (*DotEnv) GetUint64

func (e *DotEnv) GetUint64(key string) uint64

func (*DotEnv) IsSet

func (e *DotEnv) IsSet(key string) bool

func (*DotEnv) Load

func (e *DotEnv) Load(files ...string) error

func (*DotEnv) LoadWithDecoder

func (e *DotEnv) LoadWithDecoder(decoder Decoder, files ...string) error

func (*DotEnv) LookUp

func (e *DotEnv) LookUp(key string) (any, bool)

func (*DotEnv) Save deprecated

func (e *DotEnv) Save() error

Deprecated: to be removed in v2.0.0

Save writes the current configuration to a file.

func (*DotEnv) Set

func (e *DotEnv) Set(key string, value any)

func (*DotEnv) SetConfigFile

func (e *DotEnv) SetConfigFile(configFile string)

func (*DotEnv) SetPrefix

func (e *DotEnv) SetPrefix(prefix string)

func (*DotEnv) Unmarshal

func (e *DotEnv) Unmarshal(v any) (err error)

func (*DotEnv) Write

func (e *DotEnv) Write(key string, value any) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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