It is more about studying Go reflection approach than to create something better than what already exists, but an useful package with a complete documentation may come out of this.
envtags is a package to use struct tags to automatically load environment variables on them.
Go >= 1.18
Define a struct with the env
tag on exported fields to bind the fields with environment variables
On an environment with the corresponding variables set, bind the struct to these variables using the method envtags.Set()
export BAR="13"
package main
import "github.com/taciogt/envtags"
type Config struct {
Foo int `env:"BAR"`
}
func main() {
var config Config
if err := envtags.Set(&config); err != nil {
log.Fatal(err)
}
}
If the environment variable value can not be parsed to the field type, an envtags.ErrInvalidTypeConversion
error is returned.
If the field type is not supported, an envtags.ErrParserNotAvailable
is returned.
- Primitives
bool
string
int
,int64
,int32
,int16
,int8
uint
,uint64
,uint32
,uint16
,uint8
float32
,float64
complex64
,complex128
byte
- Non primitives
structs
Better test output with:
go install github.com/rakyll/gotest
Inspired by
- https://github.com/kelseyhightower/envconfig/blob/master/envconfig.go
- https://github.com/caarlos0/env
References