If you have a usecase of having different config path based on environment or whatsoever, all the paths can be configured and last valid path will be used to read the configuration.
import "github.com/ilyakaznacheev/cleanenv"
type ConfigDatabase struct {
Port string `yaml:"port" env:"PORT" env-default:"5432"`
Host string `yaml:"host" env:"HOST" env-default:"localhost"`
Name string `yaml:"name" env:"NAME" env-default:"postgres"`
User string `yaml:"user" env:"USER" env-default:"user"`
Password string `yaml:"password" env:"PASSWORD"`
}
var cfg ConfigDatabase
cleanenv.AddConfigPath("config.yml")
cleanenv.AddConfigPath("/dev/config.yml")
cleanenv.AddConfigPath("/prod/config.yml")
err := cleanenv.Read(&cfg)
if err != nil {
...
}
This will do the following:
reads last valid path among added paths.
parse configuration file according to YAML format (yaml tag in this case);
reads environment variables and overwrites values from the file with the values which was found in the environment (env tag);
if no value was found on the first two steps, the field will be filled with the default value (env-default tag) if it is set.
FEAT
This will do the following:
yaml
tag in this case);env
tag);env-default
tag) if it is set.