settings is a Go package that simplifies configuration management for your application. It automatically loads environment variables into your configuration structs, supports default values, and validates fields using standard validate tags. With settings, you can define your application's configuration in a type-safe, declarative way—eliminating boilerplate code and reducing the risk of misconfiguration.
Use go get to install the package:
go get github.com/kaatinga/settingsThen, 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():
typeSettingsstruct {
Portstring`env:"PORT" validate:"numeric"`Databasestring`env:"DATABASE"`CacheSizebyte`env:"CACHE_SIZE" default:"50"`LaunchModestring`env:"LAUNCH_MODE"`
}
varsettingsSettingserr:=Load(&settings)
iferr!=nil {
returnerr
}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 |
| []string | []string |
| []byte | []byte |
Nested structs can be added via pointer or without pointer. Example:
typeModel2struct {
CacheSizebyte`env:"CACHE_SIZE"`
}
typeModel3struct {
Portstring`env:"PORT validate:"numeric"`
}
typeModel1struct {
Databasestring`env:"DATABASE"`Model2*Model2Model3Model3
}The nested structs that added via pointer must not be necessarily initialized:
varsettingsModel1iferr:=Load(&settings); err!=nil {
returnerr
}Nonetheless, if you want, you can do it.
varsettings=Model1{Model2: new(Model2)}
iferr:=Load(&settings); err!=nil {
returnerr
}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)
iferr!=nil {
returnerr
}Otherwise, the function returns error.