cleanenv
cleanenv copied to clipboard
Add functions for prefixed environment variables
Thanks so much for this repo, I've found it extremely useful!
This PR adds functionality for easily working with environment variables that share a common prefix, as is often the case for the configuration of an application. For example, consider (modified from the README in the current master branch):
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"`
}
The environment variables serving as the configuration for the database application might share a common prefix such as DB or APPNAME (e.g., DB_PORT, DB_HOST, etc). To cleanly and easily handle this case, rather than repeating the prefix in the struct tags (hindering readability), we add the functions:
func ReadConfigWithPrefix(path string, prefix string, cfg interface{}) errorfunc ReadEnvWithPrefix(prefix string, cfg interface{}) errorfunc UpdateEnvWithPrefix(prefix string, cfg interface{}) error
so that the prefix is specified once on read. Following the example above, we read the prefixed environment variables as:
var cfg ConfigDatabase
err := cleanenv.ReadEnvWithPrefix("appname", &cfg)
if err != nil {
...
}
For completeness, this PR also adds the following description function:
func GetDescriptionWithPrefix(cfg interface{}, prefix string, headerText *string) (string, error)
This functionality is intended to work similar to the prefix functionality of kelseyhightower/envconfig
Thanks for considering this PR, and I'm more than happy to iterate on any feedback you might have.
Codecov Report
Merging #65 (ee445ab) into master (ce3ee7f) will decrease coverage by
0.14%. The diff coverage is91.30%.
@@ Coverage Diff @@
## master #65 +/- ##
==========================================
- Coverage 89.79% 89.65% -0.15%
==========================================
Files 1 1
Lines 245 261 +16
==========================================
+ Hits 220 234 +14
- Misses 17 19 +2
Partials 8 8
| Impacted Files | Coverage Δ | |
|---|---|---|
| cleanenv.go | 89.65% <91.30%> (-0.15%) |
:arrow_down: |
Continue to review full report at Codecov.
Legend - Click here to learn more
Δ = absolute <relative> (impact),ø = not affected,? = missing dataPowered by Codecov. Last update ce3ee7f...ee445ab. Read the comment docs.
@ilyakaznacheev Can we add this feature?