env

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2024 License: MIT Imports: 8 Imported by: 0

README

env

streamline and simplify the way you work with environment variables


Features

  • .env File Support: Load variables from a .env file and/or any other file(s)
  • Type Conversions: Easily convert environment variables to Go types
  • Validation: Check common configuration errors (e.g. as.PortNo to enforce 0 <= X <= 65535)
  • Testing: Convenient testing utilities

Installation

go get github.com/blugnu/env

Example Usage

Override Default Configuration

Demonstrates the use of the env.Override function to replace a default configuration value with a value parsed from an environment variable:

    port := 8080
    if _, err := env.Override(&port, "SERVICE_PORT", as.PortNo); err != nil {
        log.Fatal(err)
    }
    log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))

Parse a Required Configuration Value

Demonstrates the use of the env.Parse function to parse a required configuration value from an environment variable:

    authURL, err := env.Parse("AUTH_SERVICE_URL", as.AbsoluteURL)
    if err != nil {
        log.Fatal(err)
    }

Load Configuration from a File

Demonstrates the use of the env.Load function to load configuration:

by default, with no filename(s) specified, the Load() function loads configuration from a .env file.

    if err := env.Load(); err != nil {
        log.Fatal(err)
    }

Preserve Environment Variables in a Test

Demonstrates the use of defer env.State().Reset() to preserve environment variables during a test:

    func TestSomething(t *testing.T) {
        // ARRANGE
        defer env.State().Reset()
        env.Vars{
            "SOME_VAR": "some value",
            "ANOTHER_VAR": "another value",
        }.Set()

        // ACT
        SomeFuncUsingEnvVars()

        // ASSERT
        ...
    }

Contributing

Contributions are welcome! Please feel free to submit a pull request.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotSet            = errors.New("not set")
	ErrSetVariableFailed = errors.New("set variable failed")
)

Functions

func Clear

func Clear()

Clear removes all environment variables.

func Get

func Get(name string) string

Get returns the value of the environment variable with the given name. If the variable is not set an empty string is returned.

To differentiate between a variable that is not set and a variable that is set to an empty string, use the `Lookup` function.

parameters

name string   // the name of the environment variable

returns

string   // the value of the environment variable

func Load

func Load(files ...string) error

Load loads environment variables from one or more files. Files should be formatted as a list of key-value pairs, one per line, separated by an equals sign. Lines that are empty or start with a hash (#) are ignored.

example file format

# this is a comment
NAME1=value1
NAME2=value2

# this is another comment
NAME3=value3

parameters

files: ...string    // 0..n file path(s)

returns

error      // an error that wraps all errors that occurred while loading variables;
           // if no errors occurred the result is nil

The joined errors will be in the order that the files were specified and will be wrapped with the file path that caused the error:

"path/to/file: error"

.env file

The function will always attempt to load variables from a ".env" file.

If ".env" (or "./.env") is included in the files parameter it will be loaded in the order specified relative to other files; if the ".env" file does not exist an error will be included in the returned error.

If ".env" is not explicitly specified it will be loaded before any other files, if it exists; if it does not exist it is ignored without error.

If no files are specified the function will attempt to load variables from ".env" and will return an error if the file does not exist.

example: loading .env:

if err := Load(); err != nil {
	log.Fatal(err) // possibly because .env does not exist
}

example: loading .env and a specified file:

if err := Load("test.env"); err != nil {
	log.Fatal(err) // will not be because .env did not exist; could be because test.env does not exist
}

func Lookup

func Lookup(name string) (string, bool)

Lookup returns the value of the environment variable with the given name and a boolean indicating whether the variable is set. If the variable is not set the returned value is an empty string and the boolean is `false`.

If you do not need to differentiate between a variable that is not set and a variable that is set to an empty string, use the `Get` function.

parameters

name string   // the name of the environment variable

returns

string   // the value of the environment variable

bool     // true if the variable is set, false otherwise

func Override

func Override[T comparable](dest *T, name string, cnv func(string) (T, error)) (bool, error)

Override replaces the current value of some variable with the value obtained by parsing a named environment variable. If the named environment variable is not set, the target variable is not modified.

If an error occurs during parsing or conversion, the target variable is not modified and the error is returned.

The function returns true if the target variable was modified from its original value, false otherwise.

parameters

dest *T                       // a pointer to the variable to be changed

name string                   // the name of the environment variable to parse

cnv func(string) (T, error)   // a function to parse the environment variable

returns

bool    // true if the target variable was modified, false otherwise

error   // any error resulting from parsing the named environment variable

The bool result should not be relied on to determine whether an error occurred; The function will return false when:

  • an error occurs parsing or converting the named environment variable
  • the named environment variable is not set
  • the named environment variable is set with a value that is successfully parsed and converted to yield the same value as currently held in the destination variable.

Only the error result can determine if an error occurred.

func Parse

func Parse[T any](name string, cnv ConversionFunc[T]) (T, error)

Parse parses the environment variable with the given name and returns a value of type T, obtained by passing the value of the environment variable to a provided conversion function.

parameters

name string             // the name of the environment variable to parse

cnv ConversionFunc[T]   // a function to parse the environment variable;
                        // the function should return a value of type T and
                        // an error if the value cannot be converted

returns

T       // the value of the environment variable; if an error occurs the
        // zero value of T is returned

error   // any error resulting from parsing the environment variable;
        // if the error is ErrNotSet a nil error is returned

conversion functions

The `as` package provides a number of conversion functions that can be used with this function. For example, to parse an integer environment variable:

value, err := env.Parse("MY_INT_VAR", as.Int)

func Set

func Set(name, value string) error

Set sets the value of the environment variable with the given name. If the variable does not exist it is created.

parameters

name  string   // the name of the environment variable

value string   // the value to set

returns

error   // any error that occurs while setting the environment variable

func State

func State() state

State captures the current state of the environment variables. It is typically used to capture the state before a test modifies the environment so that it can be reset to the original state after the test has run (by deferring a call to the Reset method on the returned state value).

returns

state   // the current state of the environment variables

The state is captured using os.Environ().

example

func TestSomething(t *testing.T) {
	// ARRANGE
	defer env.State().Reset()
	env.Vars{
		"VAR1", "value1",
		"VAR2", "value2",
	}.Set()

	// ACT
	// ...
}

func Unset

func Unset(name ...string) error

Unset removes the environment variables with the given names. If a variable does not exist (already not set) it is ignored.

parameters

names ...string   // the names of the environment variables to remove

returns

error   // any error that occurs while unsetting the environment variables

On Unix systems (including Linux and macOS) the error is always `nil`, but on Windows systems the error may be non-nil.

Types

type ConversionFunc

type ConversionFunc[T any] func(string) (T, error)

ConversionFunc is a function that converts a string to a value of type T. It is the type of the conversion function used by the Parse and Override functions.

parameters

string string   // the string to convert

returns

T       // the converted value

error   // any error that occurs during conversion

type InvalidValueError

type InvalidValueError struct {
	Value string
	Err   error
}

InvalidValueError is an error type that represents an invalid value. The Value field contains the invalid value, and the Err field contains the error that caused the value to be invalid.

func (InvalidValueError) Error

func (e InvalidValueError) Error() string

Error returns a string representation of the error in the form:

env.InvalidValueError: <value>: <error>

If the Value field is empty:

env.InvalidValueError: <error>

If the Err field is nil:

env.InvalidValueError: <value>

If both fields are empty:

env.InvalidValueError

func (InvalidValueError) Is

func (e InvalidValueError) Is(target error) bool

Is reports whether the target error is a match for the receiver. To be a match, the target must:

  • be an InvalidValueError
  • the target Value field must match the receiver's Value, or be empty
  • the target Err field must satisfy errors.Is with respect to the receiver Err, or be nil

func (InvalidValueError) Unwrap

func (e InvalidValueError) Unwrap() error

Unwrap returns the error that caused the invalid value error.

type ParseError

type ParseError struct {
	VariableName string
	Err          error
}

ParseError is an error that wraps an error occurring while parsing an environment variable. It includes the name of the variable being parsed at the time of the error.

func (ParseError) Error

func (e ParseError) Error() string

Error returns a string representation of the error in the form:

env.ParseError: <variable name>: <error>

If the VariableName field is empty:

env.ParseError: <error>

If the Err field is nil:

env.ParseError: <variable name>

If both fields are empty:

env.ParseError

func (ParseError) Is

func (e ParseError) Is(target error) bool

Is reports whether the target error is a match for the receiver. To be a match, the target must:

  • be a ParseError
  • the target VariableName must match the receiver's VariableName, or be empty
  • the target Err field must satisfy errors.Is with respect to the receiver Err, or be nil

func (ParseError) Unwrap

func (e ParseError) Unwrap() error

Unwrap returns the error that caused the env.Parse.

type RangeError

type RangeError[T comparable] struct {
	Min T
	Max T
}

RangeError is an error type that represents a value that is out of range; Min and Max fields identify the range of valid values.

If Min and Max are both the zero value of T, the error represents a general out-of-range error with no identified range.

func (RangeError[T]) Error

func (e RangeError[T]) Error() string

Error returns a string representation of the error in the form:

out of range: <Min> <= (x) <= <Max>

If Min and Max are both the zero value of T:

out of range

func (RangeError[T]) Is

func (e RangeError[T]) Is(target error) bool

Is reports whether the target error is a match for the receiver. To be a match, the target must:

  • be a RangeError
  • the target Min and Max fields must match the receiver's Min and Max fields, or be the zero value of T

type Vars

type Vars map[string]string

Vars is a map of environment variables.

func GetVars

func GetVars(names ...string) Vars

GetVars returns a map of environment variables. If no variable names are provided all environment variables are returned. If variable names are provided, only those variables are returned (if set).

parameters

names ...string   // (optional) names of environment variables to return;
                 // if no names are provided the returned map contains all
                 // environment variables.

If a name is provided that is not set in the environment it is not included in the returned map.

returns

Vars   // a map of environment variables

The returned map is a `map[string]string` where the key is the name of the environment variable and the value is the value of the environment variable.

If no environment variables are set or all specified variables names are not set, the returned map is empty.

func (Vars) Names

func (v Vars) Names() []string

Names returns the names of all variables in the map as a sorted slice.

func (Vars) Set

func (v Vars) Set() error

Set applies the variables to the environment. If an error occurs while setting a variable, the error is returned without any further variables being set.

returns

error   // any error that occurs while setting the variables

func (Vars) String

func (v Vars) String() string

String returns a string representation of the variables. The result is a string of comma delimited NAME="VALUE" entries, sorted by NAME and enclosed in [-]'s.

result

string   // a string representation of the variables in the form:

	[NAME1="VALUE1",NAME2="VALUE2",NAME3="VALUE3"]

If the map is empty the result is "[]".

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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