spf13 / viper

Go configuration with fangs
MIT License
26.88k stars 2.01k forks source link

Add support for default values in struct tags #1489

Open arvindh123 opened 1 year ago

arvindh123 commented 1 year ago

Preflight Checklist

Problem Description

Currently, Viper only supports retrieving values from environment variables and it requires the user to specify the exact environment variable name in the struct tag. It would be useful to have the ability to specify a default value in the struct tag as well, so that if the environment variable is not set, the default value will be used instead.

Proposed Solution

The proposed solution is to add a new field in the struct tag called "default" which will hold the default value. The syntax for the struct tag will be as follows:

`env:"ENV_VAR_NAME,default=DEFAULT_VALUE"`

For example:

type Config struct {
    Port int `env:"PORT,default=8080"`
}

Alternatives Considered

No response

Additional Information

No response

github-actions[bot] commented 1 year ago

👋 Thanks for reporting!

A maintainer will take a look at your issue shortly. 👀

In the meantime: We are working on Viper v2 and we would love to hear your thoughts about what you like or don't like about Viper, so we can improve or fix those issues.

⏰ If you have a couple minutes, please take some time and share your thoughts: https://forms.gle/R6faU74qPRPAzchZ9

📣 If you've already given us your feedback, you can still help by spreading the news, either by sharing the above link or telling people about this on Twitter:

https://twitter.com/sagikazarmark/status/1306904078967074816

Thank you! ❤️

tkrop commented 1 month ago

I love this proposal, and I definitely would like some support for setting default values using tags, however reusing the env-tag seems to create redundant information that makes the name of environment variables unclear. So using something simpler as go-defaults default-tag during initial creation of the root struct would be more sufficient.

This would result in support for

type Config struct {
    Port int `default=8080"`
}

However, since go-defaults can actually be applied to the input struct before being inserted, it actually turns out that the core issue is to define the environment variable names for default in viper. So one would actually just need to extract a key value list of the base struct to setup defaults.

Viper support for such a feature could therefor just consist of allowing to register a default configuration object that is providing all basic default values. In the end it than does not matter whether this template is provided by go-defaults or any other way to setup a default structure.