env

package module
v0.2.3 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2019 License: MIT Imports: 9 Imported by: 0

README

env

Credit - this repo is a heavily modified version of env by https://github.com/caarlos0 . We just reworked the feature set to meet our needs.

env utility functions

This repo provides some simple utilities for dealing with environment variables. There are some basic functions that are simple wrappers to the "os" package's env functions. These include:

err   = env.Set("KEY", "secret_key")
err   = env.Unset("KEY")
value = env.Get("OTHER_KEY")
value = env.GetOr("OTHER_KEY", "value returned if OTHER_KEY does not exist")
value = env.MustGet("KEY")  // panics if KEY does not exist

Parse environment vars into a struct

A much more powerful approach is to populate an annotated struct with values from the environment.

Take the following example:

type ClientConfig struct {
	Endpoint                  []string      `env:"ENDPOINT,required"`
	HealthCheck               bool          `env:"HEALTH_CHECK" envDefault:"true"`
	HealthCheckTimeout        time.Duration `env:"HEALTH_CHECK_TIMEOUT" envDefault:"1s"`
}

This anotated struct can then be populated with the appropiate environment variables but using the following command:

	cfg := ClientConfig{}
	err := env.Parse(&cfg)

Using a prefix

If the struct you are populating is part of a library you may want to have parse the same struct but with different values. You can do this by using a prfic when parsing.

	cfg := ClientConfig{}
	err := env.ParseWithPrefix(&cfg, "CLIENT2_")

In this case the parser would look for the envionment variables CLIENT2_ENDPOINT, CLIENT2_HEALTH_CHECK, etc.

Supported types and defaults

The environment variables are Parsed to go into the appropiate types (or an err is thrown if it can not do so). This sames you from writing a some basic validations on envirnment varaibles.

The library has built-in support for the following types:

  • string
  • int
  • uint
  • int64
  • bool
  • float32
  • float64
  • time.Duration
  • url.URL
  • []string
  • []int
  • []bool
  • []float32
  • []float64
  • []time.Duration
  • []url.URL
Optional tags

The required tag will cause an error if the environment variable does not exist: `env:"ENDPOINT,required"`

The envDefault tag will allow you to provide a default value to use if the environment variable does not exist: `env:"HEALTH_CHECK" envDefault:"true"`

When assigning to a slice type the "," is used to seperate fields. You can override this with the envSeparator:":" tag to use some other character.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotAStructPtr is returned if you pass something that is not a pointer to a
	// Struct to Parse
	ErrNotAStructPtr = errors.New("Expected a pointer to a Struct")
	// ErrUnsupportedType if the struct field type is not supported by env
	ErrUnsupportedType = errors.New("Type is not supported")
	// ErrUnsupportedSliceType if the slice element type is not supported by env
	ErrUnsupportedSliceType = errors.New("Unsupported slice type")
	// OnEnvVarSet is an optional convenience callback, such as for logging purposes.
	// If not nil, it's called after successfully setting the given field from the given value.
	OnEnvVarSet func(reflect.StructField, string)
)

Functions

func Get added in v0.2.0

func Get(key string) string

Get - get an environment variable, empty string if does not exist

func GetOr added in v0.2.0

func GetOr(key, defaultValue string) string

GetOr - get an environment variable or return default value if does not exist

func MustGet added in v0.2.0

func MustGet(key string) string

MustGet - get an environment variable or panic if does not exist

func Parse

func Parse(v interface{}) error

Parse parses a struct containing `env` tags and loads its values from environment variables.

Example
type config struct {
	Home         string `env:"HOME"`
	Port         int    `env:"PORT" envDefault:"3000"`
	IsProduction bool   `env:"PRODUCTION"`
}
os.Setenv("HOME", "/tmp/fakehome")
cfg := config{}
_ = Parse(&cfg)
fmt.Println(cfg)
Output:
{/tmp/fakehome 3000 false}

func ParseWithFuncs

func ParseWithFuncs(v interface{}, funcMap CustomParsers) error

ParseWithFuncs is the same as `Parse` except it also allows the user to pass in custom parsers.

func ParseWithPrefix

func ParseWithPrefix(v interface{}, prefix string) error

ParseWithPrefix parses a struct containing `env` tags and loads its values from environment variables. The actual env vars looked up include the passed in prefix.

func ParseWithPrefixFuncs

func ParseWithPrefixFuncs(v interface{}, prefix string, funcMap CustomParsers) error

ParseWithPrefixFuncs is the same as `ParseWithPrefix` except it also allows the user to pass in custom parsers.

func Set added in v0.2.0

func Set(key, value string) error

Set - sets an environment variable

func Unset added in v0.2.0

func Unset(key string) error

Unset - unsets an environment variable

Types

type CustomParsers

type CustomParsers map[reflect.Type]ParserFunc

CustomParsers is a friendly name for the type that `ParseWithFuncs()` accepts

type ParserFunc

type ParserFunc func(v string) (interface{}, error)

ParserFunc defines the signature of a function that can be used within `CustomParsers`

Jump to

Keyboard shortcuts

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