ilyakaznacheev / cleanenv

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

feat: multiple config filepath support. #149

Open pansachin opened 2 months ago

pansachin commented 2 months ago

FEAT

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:

  1. reads last valid path among added paths.
  2. parse configuration file according to YAML format (yaml tag in this case);
  3. reads environment variables and overwrites values from the file with the values which was found in the environment (env tag);
  4. 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.
pansachin commented 2 months ago

Addressing feature request: https://github.com/ilyakaznacheev/cleanenv/issues/150