dotenv

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2021 License: MIT Imports: 9 Imported by: 15

README

Dotenv Go Report Card PkgGoDev

Dotenv is a minimal Go Library for reading and writing .env configuration files. It uses renameio to perform atomic write operations making sure applications never see unexpected file content (a half-written file, or a 0-byte file).

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

  • env
  • key-value config cache/store
  • config

The config cache store is set on first read operation.

Installation

go get -u github.com/profclems/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
Reading .env files
package main

import (
    "log"
    
    "github.com/profclems/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.LoadConfig()
  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
}
Writing .env files
import (
	"fmt"
	"github.com/profclems/go-dotenv"
	"log"
)

func main() {
	// SetConfigFile explicitly defines the path, name and extension of the config file.
	dotenv.SetConfigFile("config/.env")
    dotenv.LoadConfig()

	dotenv.Set("STRONGEST_AVENGER", "Hulk")
	dotenv.Set("PLAYER_NAME", "Anon")

	err := dotenv.Save()
	if err != nil {
		log.Fatal(err)
	}

	value := dotenv.GetString("STRONGEST_AVENGER")
	fmt.Printf("%s = %s \n", "STRONGEST_AVENGER", value)

	value = dotenv.GetString("PLAYER_NAME")
	fmt.Printf("%s = %s \n", "PLAYER_NAME", value)
}

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

cfg := dotenv.Init() // This will create a Dotenv instance using .env from the current dir

or

cfg := dotenv.Init("path/to/.env")
cfg.LoadConfig()

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) : interface{}
  • GetBool(key string) : bool
  • GetFloat64(key string) : float64
  • GetInt(key string) : int
  • GetIntSlice(key string) : []int
  • GetString(key string) : string
  • GetStringMap(key string) : map[string]interface{}
  • GetStringMapString(key string) : map[string]string
  • GetStringSlice(key string) : []string
  • GetTime(key string) : time.Time
  • GetDuration(key string) : time.Duration
  • isSet(key string) : bool
  • LookUp(key string) : (interface, bool)

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

This section is empty.

Variables

View Source
var (
	DefaultConfigFile = ".env"
	DefaultSeparator  = "="
)

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 CheckFileExists

func CheckFileExists(filename string) bool

CheckFileExists returns true if a file exists and is not a directory.

func Get

func Get(key string) interface{}

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 GetFromFile

func GetFromFile(filePath, key, separator string) (interface{}, bool, error)

GetFromFile retrieves the value of the config variable named by the key from the config file If the variable is present in the environment the value (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 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 GetStringMap

func GetStringMap(key string) map[string]interface{}

GetStringMap returns the value associated with the key as a map of interfaces.

func GetStringMapString

func GetStringMapString(key string) map[string]string

GetStringMapString returns the value associated with the key as a map of strings.

func GetStringMapStringSlice

func GetStringMapStringSlice(key string) map[string][]string

GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.

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 InvalidateEnvCacheForFile

func InvalidateEnvCacheForFile(filePath string)

InvalidateEnvCacheForFile invalidates the cached content of a file

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 LoadConfig

func LoadConfig() error

LoadConfig finds and read the config file. returns os.ErrNotExist if config file does not exist

func LookUp

func LookUp(key string) (interface{}, bool)

LookUp retrieves the value of the configuration named by the key. If the variable is present in the configuration file the value (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 Save

func Save() error

Save writes the current configuration to a file.

func Set

func Set(key, value string)

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.

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 Write

func Write(key string, value interface{}) error

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

func WriteFile

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

Types

type DotEnv

type DotEnv struct {
	ConfigFile string

	// Separator is the symbol that separates a the key-value pair.
	// Default is `=`
	Separator string

	Config map[string]interface{}
	// contains filtered or unexported fields
}

DotEnv is a config registry

func GetDotEnv

func GetDotEnv() *DotEnv

GetDotEnv returns the global DotEnv instance.

func Init

func Init(file ...string) *DotEnv

Init returns an initialized DotEnv instance.. Call this function as close as possible to the start of your program (ideally in main where your config file resides) If you call Init without any args it will default to loading .env in the current path You can otherwise tell it which file to load like

dotenv.Init("file.env")

func (*DotEnv) AllowEmptyEnvVars

func (e *DotEnv) AllowEmptyEnvVars(allowEmptyEnvVars bool)

func (*DotEnv) Get

func (e *DotEnv) Get(key string) interface{}

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) GetStringMap

func (e *DotEnv) GetStringMap(key string) map[string]interface{}

func (*DotEnv) GetStringMapString

func (e *DotEnv) GetStringMapString(key string) map[string]string

func (*DotEnv) GetStringMapStringSlice

func (e *DotEnv) GetStringMapStringSlice(key string) map[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) LoadConfig

func (e *DotEnv) LoadConfig() (err error)

func (*DotEnv) LookUp

func (e *DotEnv) LookUp(key string) (interface{}, bool)

func (*DotEnv) Save

func (e *DotEnv) Save() error

func (*DotEnv) Set

func (e *DotEnv) Set(key string, value interface{})

func (*DotEnv) SetConfigFile

func (e *DotEnv) SetConfigFile(configFile string)

func (*DotEnv) SetPrefix

func (e *DotEnv) SetPrefix(prefix string)

func (*DotEnv) Write

func (e *DotEnv) Write(key string, value interface{}) error

Jump to

Keyboard shortcuts

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