Struct-based environment variable validation with batch error reporting for Go
go get github.com/philiprehberger/go-env-validatorStruct-based environment variable validation with batch error reporting for Go
go get github.com/philiprehberger/go-env-validator
import "github.com/philiprehberger/go-env-validator"
type Config struct {
Port int `env:"PORT,default=3000"`
Database string `env:"DATABASE_URL,required"`
Debug bool `env:"DEBUG,default=false"`
Env string `env:"APP_ENV,required,choices=development|staging|production"`
Timeout time.Duration `env:"TIMEOUT,default=30s"`
}
var cfg Config
if err := envvalidator.Validate(&cfg); err != nil {
log.Fatal(err)
}
fmt.Println(cfg.Port) // 3000
var cfg Config
err := envvalidator.ValidateFrom(&cfg, map[string]string{
"DATABASE_URL": "postgres://localhost/mydb",
"APP_ENV": "development",
})
if err := envvalidator.Validate(&cfg); err != nil {
var ve *envvalidator.ValidationError
if errors.As(err, &ve) {
for _, e := range ve.Errors {
fmt.Println(e)
}
}
}
stringint, int8, int16, int32, int64uint, uint8, uint16, uint32, uint64float32, float64bool — accepts true, false, 1, 0, t, f, T, F, TRUE, FALSEtime.Duration — Go duration strings (e.g., "30s", "5m", "1h30m")url.URL — parsed via url.Parseencoding.TextUnmarshalerrequired — field must be set in environmentdefault=VALUE — fallback if not set (validated against choices if both present)choices=A|B|C — restrict to specific values (whitespace around | is trimmed)| Function / Method | Description |
|---|---|
Validate(dst any) error | Populate struct from environment variables and validate |
ValidateFrom(dst any, source map[string]string) error | Populate struct from a map instead of os.Getenv |
ValidationError | Error type containing all validation errors |
(*ValidationError) Error() string | Format all collected errors as a single string |
go test ./...
go vet ./...
If you find this project useful: