The package looks up necessary environment variables and uses them to specify settings for your application. In addition, the package validates the final struct using standard validate
tags.
Use go get
to install the package:
go get github.com/kaatinga/settings
Then, import the package into your own code:
import "github.com/kaatinga/settings"
Create a settings model where you can use tags env
, default
and validate
. Announce a variable and call Load()
:
type Settings struct {
Port string `env:"PORT" validate:"numeric"`
Database string `env:"DATABASE"`
CacheSize byte `env:"CACHE_SIZE" default:"50"`
LaunchMode string `env:"LAUNCH_MODE"`
}
var settings Settings
err := Load(&settings)
if err != nil {
return err
}
The env
tag must contain the name of the related environment variable.
The default
tag contains a default value that is used in case the environment variable was not found.
The validate
tag may contain an optional validation rule fallowing the documentation of the validator package.
Type | Real type |
---|---|
string | - |
boolean | - |
~int | - |
~uint | - |
time.Duration | int64 |
Nested structs can be added via pointer or without pointer. Example:
type Model2 struct {
CacheSize byte `env:"CACHE_SIZE"`
}
type Model3 struct {
Port string `env:"PORT validate:"numeric"`
}
type Model1 struct {
Database string `env:"DATABASE"`
Model2 *Model2
Model3 Model3
}
The nested structs that added via pointer must not be necessarily initialized:
var settings Model1
if err := Load(&settings); err != nil {
return err
}
Nonetheless, if you want, you can do it.
var settings = Model1{Model2: new(Model2)}
if err := Load(&settings); err != nil {
return err
}
The configuration model has some limitations in how it is arranged and used.
If you add an empty struct to your configuration model, Load()
returns error.
The root model must be initialized and added to the Load()
signature via pointer:
err := Load(&EnvironmentSettings)
if err != nil {
return err
}
Otherwise, the function returns error.