envdecode

package module
v0.0.0-...-099f1fc Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2020 License: MIT Imports: 11 Imported by: 204

README

envdecode Travis-CI GoDoc

envdecode is a Go package for populating structs from environment variables.

envdecode uses struct tags to map environment variables to fields, allowing you you use any names you want for environment variables. envdecode will recurse into nested structs, including pointers to nested structs, but it will not allocate new pointers to structs.

API

Full API docs are available on godoc.org.

Define a struct with env struct tags:

type Config struct {
    Hostname  string `env:"SERVER_HOSTNAME,default=localhost"`
    Port      uint16 `env:"SERVER_PORT,default=8080"`

    AWS struct {
        ID        string   `env:"AWS_ACCESS_KEY_ID"`
        Secret    string   `env:"AWS_SECRET_ACCESS_KEY,required"`
        SnsTopics []string `env:"AWS_SNS_TOPICS"`
    }

    Timeout time.Duration `env:"TIMEOUT,default=1m,strict"`
}

Fields must be exported (i.e. begin with a capital letter) in order for envdecode to work with them. An error will be returned if a struct with no exported fields is decoded (including one that contains no env tags at all). Default values may be provided by appending ",default=value" to the struct tag. Required values may be marked by appending ",required" to the struct tag. Strict values may be marked by appending ",strict" which will return an error on Decode if there is an error while parsing.

Then call envdecode.Decode:

var cfg Config
err := envdecode.Decode(&cfg)

If you want all fields to act strict, you may use envdecode.StrictDecode:

var cfg Config
err := envdecode.StrictDecode(&cfg)

All parse errors will fail fast and return an error in this mode.

Supported types

  • Structs (and pointer to structs)
  • Slices of below defined types, separated by semicolon
  • bool
  • float32, float64
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • string
  • time.Duration, using the time.ParseDuration() format
  • *url.URL, using url.Parse()
  • Types those implement a Decoder interface

Custom Decoder

If you want a field to be decoded with custom behavior, you may implement the interface Decoder for the filed type.

type Config struct {
  IPAddr IP `env:"IP_ADDR"`
}

type IP net.IP

// Decode implements the interface `envdecode.Decoder`
func (i *IP) Decode(repl string) error {
  *i = net.ParseIP(repl)
  return nil
}

Decoder is the interface implemented by an object that can decode an environment variable string representation of itself.

Documentation

Overview

Package envdecode is a package for populating structs from environment variables, using struct tags.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidTarget = errors.New("target must be non-nil pointer to struct that has at least one exported field with a valid env tag.")

ErrInvalidTarget indicates that the target value passed to Decode is invalid. Target must be a non-nil pointer to a struct.

View Source
var ErrNoTargetFieldsAreSet = errors.New("none of the target fields were set from environment variables")
View Source
var FailureFunc = func(err error) {
	log.Fatalf("envdecode: an error was encountered while decoding: %v\n", err)
}

FailureFunc is called when an error is encountered during a MustDecode operation. It prints the error and terminates the process.

This variable can be assigned to another function of the user-programmer's design, allowing for graceful recovery of the problem, such as loading from a backup configuration file.

Functions

func Decode

func Decode(target interface{}) error

Decode environment variables into the provided target. The target must be a non-nil pointer to a struct. Fields in the struct must be exported, and tagged with an "env" struct tag with a value containing the name of the environment variable. An error is returned if there are no exported members tagged.

Default values may be provided by appending ",default=value" to the struct tag. Required values may be marked by appending ",required" to the struct tag. It is an error to provide both "default" and "required". Strict values may be marked by appending ",strict" which will return an error on Decode if there is an error while parsing. If everything must be strict, consider using StrictDecode instead.

All primitive types are supported, including bool, floating point, signed and unsigned integers, and string. Boolean and numeric types are decoded using the standard strconv Parse functions for those types. Structs and pointers to structs are decoded recursively. time.Duration is supported via the time.ParseDuration() function and *url.URL is supported via the url.Parse() function. Slices are supported for all above mentioned primitive types. Semicolon is used as delimiter in environment variables.

Example
type Example struct {
	// A string field, without any default
	String string `env:"EXAMPLE_STRING"`

	// A uint16 field, with a default value of 100
	Uint16 uint16 `env:"EXAMPLE_UINT16,default=100"`
}

os.Setenv("EXAMPLE_STRING", "an example!")

var e Example
err := Decode(&e)
if err != nil {
	panic(err)
}

// If TEST_STRING is set, e.String will contain its value
fmt.Println(e.String)

// If TEST_UINT16 is set, e.Uint16 will contain its value.
// Otherwise, it will contain the default value, 100.
fmt.Println(e.Uint16)
Output:

an example!
100

func MustDecode

func MustDecode(target interface{})

MustDecode calls Decode and terminates the process if any errors are encountered.

func MustStrictDecode

func MustStrictDecode(target interface{})

MustStrictDecode calls StrictDecode and terminates the process if any errors are encountered.

func StrictDecode

func StrictDecode(target interface{}) error

StrictDecode is similar to Decode except all fields will have an implicit ",strict" on all fields.

Types

type ConfigInfo

type ConfigInfo struct {
	Field        string
	EnvVar       string
	Value        string
	DefaultValue string
	HasDefault   bool
	Required     bool
	UsesEnv      bool
}

func Export

func Export(target interface{}) ([]*ConfigInfo, error)

Returns a list of final configuration metadata sorted by envvar name

type ConfigInfoSlice

type ConfigInfoSlice []*ConfigInfo

func (ConfigInfoSlice) Len

func (c ConfigInfoSlice) Len() int

func (ConfigInfoSlice) Less

func (c ConfigInfoSlice) Less(i, j int) bool

func (ConfigInfoSlice) Swap

func (c ConfigInfoSlice) Swap(i, j int)

type Decoder

type Decoder interface {
	Decode(string) error
}

Decoder is the interface implemented by an object that can decode an environment variable string representation of itself.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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