Documentation
¶
Overview ¶
Package env implements encoding and decoding of environment variables from files, the OS or other io.Reader compatible data sources. It supports unmarshalling to structs and maps, and marshaling from various types to files and io.Writer. It can also be used to load/overload environment variables into the system.
The mapping between environment variables and Go values is described in the documentation for the Marshal and Unmarshal functions.
Supported types ¶
This package uses the rawconv package to parse/unmarshal any string value to its Go type equivalent. Additionally, custom types may implement the Unmarshaler interface to implement its own unmarshalling rules, or register an unmarshaler function using rawconv.Register.
Load and overload ¶
Additional os.Environ entries can be loaded using the ReadAndLoad, OpenAndLoad, ReadAndOverload and OpenAndOverload functions. The source is read any bash style variables are replaced before being set to the system using Setenv.
Dotenv ¶
The dotenv package supports reading and loading environment variables from .env files based on active environment (e.g. prod, dev etc.). See its documentation for more information.
Writing ¶
This package can also write environment variables to an io.Writer.
Index ¶
- Constants
- func Extract(v any) (map[string]any, error)
- func Format(name string, val any) (string, error)
- func FormatShellExport(name string, val any) (string, error)
- func GetMarshalFunc(typ reflect.Type) rawconv.MarshalFunc
- func GetUnmarshalFunc(typ reflect.Type) rawconv.UnmarshalFunc
- func IsNotFound(err error) bool
- func Load(envs Mapper) error
- func Marshal(v any) ([]byte, error)
- func Overload(envs Mapper) error
- func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error)
- func Setenv(key string, val Value) error
- func Unmarshal(data []byte, v any) error
- type DecodeOptions
- type Decoder
- type EncodeOptions
- type Encoder
- type Extractor
- type Formatter
- type LookupMapper
- type Lookupper
- type LookupperFunc
- type Map
- type Mapper
- type Marshaler
- type NamedValue
- type ParseError
- type Reader
- type Replacer
- type Scanner
- type TagOptions
- type Unmarshaler
- type Value
Examples ¶
Constants ¶
const ( ErrInvalidFormat errors.Msg = "invalid format" ErrMissingEndQuote errors.Msg = "missing end quote" ErrEmptyKey errors.Msg = "empty key" )
const ErrCircularDependency errors.Msg = "circular dependency"
const ErrNotFound errors.Msg = "not found"
ErrNotFound is returned when a Lookup call cannot find a matching key.
const ErrStructExpected errors.Msg = "expected a struct type"
const ErrStructPointerExpected errors.Msg = "expected a non-nil pointer to a struct"
Variables ¶
This section is empty.
Functions ¶
func Extract ¶ added in v0.5.0
Extract environment variables names and values from the provided struct v.
func Format ¶ added in v0.5.0
Format the name and val using a standard env format and return the resulting line as a string.
func FormatShellExport ¶ added in v0.5.0
FormatShellExport the name and val using a shell compatible env format and return the resulting line as a string.
func GetMarshalFunc ¶ added in v0.5.0
func GetMarshalFunc(typ reflect.Type) rawconv.MarshalFunc
GetMarshalFunc returns the globally registered rawconv.MarshalFunc for reflect.Type typ or nil if there is none registered.
func GetUnmarshalFunc ¶ added in v0.5.0
func GetUnmarshalFunc(typ reflect.Type) rawconv.UnmarshalFunc
GetUnmarshalFunc returns the globally registered rawconv.UnmarshalFunc for reflect.Type typ or nil if there is none registered.
func IsNotFound ¶
IsNotFound tests whether the provided error is ErrNotFound.
func Load ¶ added in v0.4.0
Load sets the system's environment variables with those from the Mapper when they do not exist.
func Marshal ¶ added in v0.4.0
Marshal returns v encoded in env format.
Example ¶
type Envs struct {
Foo string
Bar struct {
Url url.URL `default:"https://example.com"`
} `env:",inline"`
Timeout time.Duration `default:"10s"`
Ip net.IP
}
b, err := Marshal(Envs{})
if err != nil {
panic(err)
}
fmt.Println(string(b))
Output: FOO= URL=https://example.com TIMEOUT=10s IP=
func Overload ¶ added in v0.4.0
Overload sets and overwrites the system's environment variables with those from the Mapper.
func ScanLines ¶
ScanLines is a bufio.SplitFunc that returns each line of text using bufio.ScanLines. Additionally, any leading or trailing whitespace is stripped from the token result. Lines that start with a #, after all leading whitespace is stripped, are treated as comments and result in an empty token result.
func Setenv ¶ added in v0.4.0
Setenv sets the Value of the environment variable named by the key using os.Setenv.
func Unmarshal ¶
Unmarshal parses the env formatted data and stores the result in the value pointed to by v. If v is nil or not a pointer, Unmarshal returns an ErrStructPointerExpected error.
Example ¶
type Envs struct {
Foo string
Bar struct {
Url url.URL
} `env:",inline"`
Timeout time.Duration `default:"10s"`
Ip net.IP
}
var data = `
FOO=bar
# ignore me
URL=http://example.com
IP=192.168.1.1`
var envs Envs
if err := Unmarshal([]byte(data), &envs); err != nil {
panic(err)
}
spew.Dump(envs)
Output: (env.Envs) { Foo: (string) (len=3) "bar", Bar: (struct { Url url.URL }) { Url: (url.URL) http://example.com }, Timeout: (time.Duration) 10s, Ip: (net.IP) (len=16 cap=16) 192.168.1.1 }
Types ¶
type DecodeOptions ¶ added in v0.4.0
type DecodeOptions struct {
// ReplaceVars
ReplaceVars bool
}
type Decoder ¶
type Decoder struct {
DecodeOptions
TagOptions
// contains filtered or unexported fields
}
A Decoder looks up environment variables while decoding them into a struct.
func NewDecoder ¶
NewDecoder returns a new Decoder which looks up environment variables from the provided Lookupper(s). When a Chain is provided it must not be empty.
func NewReaderDecoder ¶ added in v0.4.0
NewReaderDecoder returns a new Decoder similar to calling NewDecoder with NewReader as argument.
func (*Decoder) Decode ¶
Example ¶
Below example demonstrates how to decode system environment variables into a struct.
type Config struct {
Foo string
Timeout time.Duration `default:"10s"`
}
var conf Config
if err := NewDecoder(System()).Decode(&conf); err != nil {
panic(err)
}
spew.Dump(conf)
Output: (env.Config) { Foo: (string) "", Timeout: (time.Duration) 10s }
func (*Decoder) WithLookupper ¶ added in v0.4.0
WithLookupper sets the internal Lookupper to l.
func (*Decoder) WithOptions ¶ added in v0.4.0
func (d *Decoder) WithOptions(opts DecodeOptions) *Decoder
WithOptions sets DecodeOptions to the provided DecodeOptions opts.
func (*Decoder) WithTagOptions ¶ added in v0.4.0
func (d *Decoder) WithTagOptions(opts TagOptions) *Decoder
WithTagOptions sets TagOptions to the provided TagOptions opts.
type EncodeOptions ¶ added in v0.4.0
type Encoder ¶ added in v0.4.0
type Encoder struct {
EncodeOptions
TagOptions
// contains filtered or unexported fields
}
An Encoder writes env values to an output stream.
func NewEncoder ¶ added in v0.4.0
NewEncoder returns a new Encoder which writes to w.
func (*Encoder) Encode ¶ added in v0.4.0
Encode writes the env format encoding of v to the underlying io.Writer. Supported types of v are:
- Map
- map[string]Value
- map[fmt.Stringer]Value
- []NamedValue
- []envtag.Tag
- any struct type the rawconv package can handle
func (*Encoder) WithFormatter ¶ added in v0.5.0
WithFormatter sets Formatter to the provided Formatter p.
func (*Encoder) WithOptions ¶ added in v0.4.0
func (e *Encoder) WithOptions(opts EncodeOptions) *Encoder
WithOptions sets EncodeOptions to the provided EncodeOptions opts.
func (*Encoder) WithTagOptions ¶ added in v0.4.0
func (e *Encoder) WithTagOptions(opts TagOptions) *Encoder
WithTagOptions sets TagOptions to the provided TagOptions opts.
type Extractor ¶ added in v0.5.0
type Extractor struct {
TagOptions
}
An Extractor extracts environment variables names and values from a struct value.
func NewExtractor ¶ added in v0.5.0
func NewExtractor() *Extractor
NewExtractor returns a new Extractor.
func (*Extractor) Extract ¶ added in v0.5.0
Extract environment variables names and values from the provided struct v.
func (*Extractor) WithTagOptions ¶ added in v0.5.0
func (ex *Extractor) WithTagOptions(opts TagOptions) *Extractor
WithTagOptions sets TagOptions to the provided TagOptions opts.
type LookupMapper ¶
func System ¶ added in v0.4.0
func System() LookupMapper
System returns a LookupMapper which wraps the operating system's env related functions.
dec := NewDecoder(System())
type Lookupper ¶
type LookupperFunc ¶
type Map ¶
Map represents a map of key value pairs.
func Environ ¶
func Environ() Map
Environ returns a Map with the environment variables using os.Environ.
func ReplaceAll ¶ added in v0.4.0
func (Map) Lookup ¶
Lookup retrieves the Value of the environment variable named by the key. If the key is present in Map, the value (which may be empty) is returned and the boolean is true. Otherwise, the returned value will be empty and the boolean is false.
type Mapper ¶ added in v0.5.0
Mapper provides a Map of keys and values representing the environment.
type Marshaler ¶ added in v0.4.0
Marshaler is the interface implemented by types that can marshal themselves into valid env values.
type NamedValue ¶ added in v0.4.0
func Parse ¶
func Parse(str string) (NamedValue, error)
Parse parses a string containing a possible name/value pair. Any whitespace at the start and/or end of str is trimmed. It returns an empty NamedValue when the provided str, after trimming, begins with #.
func (NamedValue) GoString ¶ added in v0.4.0
func (nv NamedValue) GoString() string
type ParseError ¶
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
type Reader ¶
type Reader struct {
// contains filtered or unexported fields
}
func NewReader ¶
NewReader returns a Reader which looks up environment variables from the provided io.Reader r.
dec := NewDecoder(NewReader(r))
type Replacer ¶ added in v0.4.0
type Replacer struct {
// contains filtered or unexported fields
}
func NewReplacer ¶ added in v0.4.0
type Scanner ¶
type Scanner struct {
// contains filtered or unexported fields
}
func NewScanner ¶
NewScanner returns a new Scanner which wraps a bufio.Scanner that reads from io.Reader r. The split function defaults to ScanLines. Successive calls to the Scan method will (just like bufio.Scanner) step through the 'tokens' of the read bytes, skipping the bytes between the tokens.
func (*Scanner) Bytes ¶
Bytes returns the most recent token generated by a call to Scan. The underlying array may point to data that will be overwritten by a subsequent call to Scan. It does no allocation.
func (*Scanner) NamedValue ¶ added in v0.4.0
func (s *Scanner) NamedValue() (NamedValue, error)
NamedValue returns the parsed NamedValue from the most recent token generated by a call to Scan.
func (*Scanner) Scan ¶
Scan advances the scanner to the next token, which will then be available through the Bytes or Text method. The token is guaranteed to not be empty. See bufio.Scanner for additional details.
type TagOptions ¶ added in v0.4.0
TagOptions is an alias of envtag.Options.
type Unmarshaler ¶
Unmarshaler is the interface implemented by types that can unmarshal a textual representation of themselves. It is similar to encoding.TextUnmarshaler.
type Value ¶
Value is an alias of rawconv.Value.
func Getenv ¶
Getenv retrieves the Value of the environment variable named by the key using os.Getenv.
func Lookup ¶
Lookup retrieves the Value of the environment variable named by the key from any of the provided Lookupper(s). If the key is present the value (which may be empty) is returned and the error is nil. Otherwise, the returned value will be empty and the error ErrNotFound.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package dotenv supports reading and loading environment variables from .env files based on active environment (e.g.
|
Package dotenv supports reading and loading environment variables from .env files based on active environment (e.g. |
|
Package envfile provides tools to read and load environment variables from files.
|
Package envfile provides tools to read and load environment variables from files. |
|
Package envtag provides tools to parse tags from strings or struct fields.
|
Package envtag provides tools to parse tags from strings or struct fields. |
|
internal
|
|