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 IsNotFound(err error) bool
- func Load(envs Environment) error
- func Marshal(v any) ([]byte, error)
- func Overload(envs Environment) 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 Environment
- type EnvironmentLookupper
- type Lookupper
- type LookupperFunc
- type Map
- 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 IsNotFound ¶
IsNotFound tests whether the provided error is ErrNotFound.
func Load ¶ added in v0.4.0
func Load(envs Environment) error
Load sets the system's environment variables with those from the Map 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
func Overload(envs Environment) error
Overload sets and overwrites the system's environment variables with those from the Map.
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 changes the internal Lookupper to l.
func (*Decoder) WithOptions ¶ added in v0.4.0
func (d *Decoder) WithOptions(opts DecodeOptions) *Decoder
WithOptions changes the internal DecodeOptions to opts.
func (*Decoder) WithTagOptions ¶ added in v0.4.0
func (d *Decoder) WithTagOptions(opts TagOptions) *Decoder
WithTagOptions changes the internal TagOptions to 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) WithOptions ¶ added in v0.4.0
func (e *Encoder) WithOptions(opts EncodeOptions) *Encoder
WithOptions changes the internal EncodeOptions to opts.
func (*Encoder) WithTagOptions ¶ added in v0.4.0
func (e *Encoder) WithTagOptions(opts TagOptions) *Encoder
WithTagOptions changes the internal TagOptions to opts.
type Environment ¶ added in v0.4.0
Environment provides a Map of keys and values representing the environment.
type EnvironmentLookupper ¶ added in v0.4.0
type EnvironmentLookupper interface { Lookupper Environment }
func System ¶ added in v0.4.0
func System() EnvironmentLookupper
System returns an EnvironmentLookupper 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.
func (Map) Merge ¶
Merge any map of strings into this Map. Existing keys in Map are overwritten with the value of the key in src.
func (Map) MergeValues ¶
MergeValues merges a map of Value into this Map. Existing keys in Map m are overwritten with the value of the key in src.
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 key 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.
type TagOptions ¶ added in v0.4.0
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.
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
|
|