cleanenv
cleanenv copied to clipboard
Can not overwrite variable
I'm having hard time overrriding a value from enviroment variable. Here is what I want. I want to read config from a enviroment file. Then read enviroment varialbes and overwrite them even If they exist in the config file. The following code does not overwrite value from enviroment varialbe as it supposed to:
type ConfigDatabase struct {
Port string `env:"PORT" env-default:"5432"`
Host string `env:"HOST" env-default:"localhost"`
Name string `env:"NAME" env-default:"postgres"`
User string `env:"USER" env-default:"user"`
Password string `env:"PASSWORD"`
}
var cfg ConfigDatabase
err := cleanenv.ReadConfig("config.env", &cfg)
if err != nil {
log.Println(err)
}
err1 := cleanenv.ReadEnv(&cfg)
if err1 != nil {
log.Println(err1)
}
fmt.Println(cfg)
Even witih cleanenv.UpdateEnv It still does not work. To my understanding, Each Read* function should overwrite the previous values.
Also the env-update struct tag is not working either.
Password string `env:"PASSWORD" env-upd`
I get an warning in VSCode
struct field tag env:"PASSWORD" env-upd not compatible with reflect.StructTag.Get: bad syntax for struct tag pair
bump I also get this error but with env-required.
@imraan-go I think the documentation is not up to date. If you have a look at the unit tests , its working -> https://github.com/ilyakaznacheev/cleanenv/blob/master/cleanenv_test.go#L77
Well, the answer is simple - when you use an environment file, it actually sets the environment variables according to the data in the file. So basically you override the existing environment with k-v pairs from this file.
This is kinda unclear, so I'll add this to the documentation.
There is a good question, should read the .env file and set the values to the actual environment? My opinion is yes because it is how we use env files. But someone may disagree, so I'd like to discuss it.
Anyway, I'll not change the current behavior (for now), since it may break some applications which rely on this logic. If you want overriding work, use either the env file or env variables, or else the env file wins.
Anyway, it looks like a bit of a side effect, I'll think about how to fix that without breaking existing apps.
I would say that the current behavior is not obvious and I would expect environment variables to take priority over the configuration in the file.
You could add some options that would allow users to change the priority between reading different sources of variables