ilyakaznacheev / cleanenv

✨Clean and minimalistic environment configuration reader for Golang
MIT License
1.66k stars 115 forks source link

Set but empty Environment Variables don't raise an error #118

Closed YoungOak closed 6 months ago

YoungOak commented 1 year ago

Found that even if my struct has the env-required or env-default set for the fields, if the environment variable was set but left empty, no error is rised, default value is not set either if used. Eg:

Lets say this var was set like this: export MY_VAR=""

If my struct were:

type MyVars struct {
    MyVar string `env:"MY_VAR" env-required:"true"`
}

No error is raised at all, and i get and empty struct. If otherwise my struct had a default:

type MyVars struct {
    MyVar string `env:"MY_VAR" env-default:"something"`
}

Id get an empty struct again rather than one with the default value.

Is this an expected behavior or could it be improved on?

saddit commented 1 year ago

It's an expected behavior. When reading variables from env, the program determines whether a value exists by determining whether the pointer is nil.

var envVal *string

if rawVal, ok := env.Lookup("foo"); ok {
    envVal = &rawVal
}