Documentation
¶
Overview ¶
Package env is a small package for managing environment variables.
Unlike the standard os.Getenv approach, this package models itself after the encoding/json package, providing a way to marshal and unmarshal environment variables into a structured format using env tags.
Index ¶
- func Unmarshal(out any, opts ...UnmarshalOption) error
- type Environment
- func (e Environment) Contains(key string) bool
- func (e Environment) Export()
- func (e Environment) ExportCmd(cmd *exec.Cmd)
- func (e Environment) Get(key string) Value
- func (e Environment) Lookup(key string) (value Value, ok bool)
- func (e *Environment) Set(key string, value Value)
- func (e Environment) Unmarshal(out any, opts ...UnmarshalOption) error
- func (e Environment) Unset(key string)
- type InvalidTagOptionError
- type InvalidTypeError
- type ParseError
- type RequirementError
- type UnmarshalOption
- type Unmarshaler
- type Value
- func (v Value) Bool() (bool, error)
- func (v Value) Duration() (time.Duration, error)
- func (v Value) Float32() (float32, error)
- func (v Value) Float64() (float64, error)
- func (v Value) Int() (int, error)
- func (v Value) Int8() (int8, error)
- func (v Value) Int16() (int16, error)
- func (v Value) Int32() (int32, error)
- func (v Value) Int64() (int64, error)
- func (v Value) String() string
- func (v Value) Time() (time.Time, error)
- func (v Value) Uint() (uint, error)
- func (v Value) Uint8() (uint8, error)
- func (v Value) Uint16() (uint16, error)
- func (v Value) Uint32() (uint32, error)
- func (v Value) Uint64() (uint64, error)
- func (v Value) Unmarshal(value any, opts ...UnmarshalOption) error
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Unmarshal ¶
func Unmarshal(out any, opts ...UnmarshalOption) error
Unmarshal reads values from the current environment and parses values into the provided output struct.
Fields on the output struct are interpreted based on `env` tag options which defines the variable key to read from, and any additional options. If this tag is not set, the field name is converted to screaming snake case and used instead (e.g. the field `ProjectName` would use the environment variable `PROJECT_NAME`). Unexported fields are ignored.
A nil `out` parameter is valid and will return nil without error.
This function supports parsing values from the environment for the following types:
- string types
- integral types (byte, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64)
- floating point types (float32, float64)
- boolean types
- time.Duration (using time.ParseDuration format)
- time.Time (using time.Parse, using all common time format layouts)
- Unmarshaler
- encoding.TextUnmarshaler
- slices of any of the above supported types
This makes use of the `env` tag to specify the environment variable key to read from.
Fields may be marked as required by adding the `required` option to the tag. Slices may have custom separators (default is ',') that may be specified with the `sep` option. For example:
type Environment struct {
ProjectName string `env:"PROJECT_NAME,required"`
Timeout time.Duration `env:"TIMEOUT"`
Path []string `env:"PATH,required,sep=;"`
}
On error, this function may return one of the following error types:
- RequirementError when a required environment variable was not defined.
- ParseError when a value cannot be parsed from an environment variable.
- InvalidTypeError when an unsupported type is used without defining it as a [Marshaler] or encoding.TextUnmarshaler.
- InvalidTagOptionError when an invalid/unsupported tag option is used.
Example ¶
package main
import (
"fmt"
"log"
"os"
"time"
"rodusek.dev/pkg/env"
)
func main() {
type Environment struct {
ProjectName string `env:"PROJECT_NAME,required"`
Timeout time.Duration `env:"TIMEOUT"`
Path []string `env:"PATH,required,sep=;"`
}
os.Setenv("PROJECT_NAME", "example")
environment := Environment{
Timeout: 5 * time.Second, // Setting a default for if not specified
}
if err := env.Unmarshal(&environment); err != nil {
log.Fatalf("failed to unmarshal environment: %v", err)
}
fmt.Println(environment.ProjectName, environment.Timeout)
}
Output: example 5s
Types ¶
type Environment ¶
Environment is a map of environment variables.
This map is a simple key-value store where the key is the environment variable name and the value is the environment variable value. It may be used to unmarshal values without requiring the real environment to be modified, such as through the dotenv sub-package.
This type is not thread-safe. If you need to write to the access while concurrently reading it, you should use a mutex to protect it.
func Load ¶
func Load() Environment
Load the current environment variables into a new Environment instance.
The returned map will contain all the elements returned from os.Environ.
func (Environment) Contains ¶
func (e Environment) Contains(key string) bool
Contains returns true if the environment variable with the given key exists.
func (Environment) Export ¶
func (e Environment) Export()
Export sets the environment variables in the current process.
func (Environment) ExportCmd ¶
func (e Environment) ExportCmd(cmd *exec.Cmd)
ExportCmd sets the environment variables into the specified subprocess command object.
func (Environment) Get ¶
func (e Environment) Get(key string) Value
Get the value of the environment variable with the given key, falling back to the real environment as if by using os.Getenv.
Note: To search this without falling back to os.Getenv, use the map access notation instead:
value := env[key]
func (Environment) Lookup ¶
func (e Environment) Lookup(key string) (value Value, ok bool)
Lookup the value of the environment variable with the given key.
If the environment variable does not exist, it will be looked up in the real environment using os.LookupEnv. If it still does not exist, the second return value will be false.
Note: To search this without falling back to os.LookupEnv, use the map access notation instead:
value, ok := env[key]
func (*Environment) Set ¶
func (e *Environment) Set(key string, value Value)
Set the value of the environment variable with the given key.
func (Environment) Unmarshal ¶
func (e Environment) Unmarshal(out any, opts ...UnmarshalOption) error
Unmarshal the environment variables into the given struct. See the documentation for Unmarshal for more details on what can be returned from this function.
func (Environment) Unset ¶
func (e Environment) Unset(key string)
Unset the environment variable with the given key.
type InvalidTagOptionError ¶
type InvalidTagOptionError struct {
// Key is the environment variable key that caused the error.
Key string
// Option is the tag option that caused the error.
Option string
// Type is the type of the field the error occurred on.
Type reflect.Type
// Field is the struct field that caused the error. This is nil if the type
// is not a struct field.
Field *reflect.StructField
}
InvalidTagOptionError is an error that occurs when an invalid tag option is used in a struct field tag.
func (*InvalidTagOptionError) Error ¶
func (e *InvalidTagOptionError) Error() string
type InvalidTypeError ¶
type InvalidTypeError struct {
// Key is the environment variable key assigned to the type.
Key string
// Type is the type that caused the error.
Type reflect.Type
// Field is the struct field that caused the error. This is nil if the type
// is not a struct field.
Field *reflect.StructField
}
InvalidTypeError is an error that occurs when an unsupported type is used. This can occur when a struct field is not a pointer or when a struct field is not a supported type.
func (*InvalidTypeError) Error ¶
func (e *InvalidTypeError) Error() string
type ParseError ¶
type ParseError struct {
// Key is the environment variable key that caused the error.
Key string
// Value is the value that caused the error.
Value string
// Type is the type that caused the error.
Type reflect.Type
// Err is the underlying error that was triggered during parsing.
Err error
}
ParseError is an error that occurs when a value cannot be parsed from an environment variable.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶
func (e *ParseError) Unwrap() error
type RequirementError ¶
RequirementError is an error that occurs when a required environment variable is missing.
func (*RequirementError) Error ¶
func (e *RequirementError) Error() string
type UnmarshalOption ¶
type UnmarshalOption interface {
// contains filtered or unexported methods
}
UnmarshalOption is an option that can be passed to the Unmarshal or Environment.Unmarshal functions.
func Separator ¶
func Separator(sep string) UnmarshalOption
Separator returns an UnmarshalOption that sets the default separator for splitting values for slice values.
This is the _only_ way to set a custom separator when using Value's unmarshal functionality, since values are not part of a struct and therefore cannot provide the `env` sep tag.
type Unmarshaler ¶
type Unmarshaler interface {
// UnmarshalEnv unmarshals the provided value from an environment string into
// the implementing type.
UnmarshalEnv(value []byte) error
}
Unmarshaler is an interface that allows for custom unmarshaling of environment variables.
type Value ¶
type Value string
Value represents an environment variable value, and provides basic utilities for converting to commonly used types.
func (Value) Bool ¶
Bool returns the value as a bool and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Duration ¶
Duration returns the value as a time.Duration and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Float32 ¶
Float32 returns the value as a float32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Float64 ¶
Float64 returns the value as a float64 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Int ¶
Int returns the value as an int and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Int8 ¶
Int8 returns the value as an int8 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Int16 ¶
Int16 returns the value as an int16 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Int32 ¶
Int32 returns the value as an int32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Int64 ¶
Int64 returns the value as an int64 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Time ¶
Time returns the value as a time.Time and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Uint ¶
Uint returns the value as an uint and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Uint8 ¶
Uint8 returns the value as an uint8 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Uint16 ¶
Uint16 returns the value as an uint16 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.
func (Value) Uint32 ¶
Uint32 returns the value as an uint32 and returns any errors that may occur. See Unmarshal for more details on the possible errors that may be returned.