Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: new methods viper.GetOrDefault() returning default value if the config is not set #1459

Closed
1 task done
Bin-Huang opened this issue Nov 4, 2022 · 4 comments
Labels
kind/enhancement New feature or request

Comments

@Bin-Huang
Copy link

Bin-Huang commented Nov 4, 2022

Preflight Checklist

  • I have searched the issue tracker for an issue that matches the one I want to file, without success.

Problem Description

Sometimes we need to get some unimportant configuration, if the configuration is not set, then use the default value.

Now we have to call two methods to do this, SetDefault() and then Get(), which makes the code a bit unreadable:

viper.SetDefault("LOGGER_NAME", "deadletter-recorder")
logName := viper.GetString("LOGGER_NAME")

viper.SetDefault("LOGGER_LEVEL", "info")
logLevel := viper.GetString("LOGGER_LEVEL")

viper.SetDefault("LOGGER_LOG_DIR", "./log")
logDir := viper.GetString("LOGGER_LOG_DIR")

Proposed Solution

It will be better if there are some methods just like GetOrDefault(), GetStringOrDefault(), GetBoolOrDefault()...

logName := viper.GetStringOrDefault("LOGGER_NAME", "deadletter-recorder")

logLevel := viper.GetStringOrDefault("LOGGER_LEVEL", "info")

logDir := viper.GetStringOrDefault("LOGGER_LOG_DIR", "./log")

Alternatives Considered

No response

Additional Information

I'm interested in implementing it if the idea is considered worthwhile.

@Bin-Huang Bin-Huang added the kind/enhancement New feature or request label Nov 4, 2022
@github-actions
Copy link

github-actions bot commented Nov 4, 2022

👋 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! ❤️

@sagikazarmark
Copy link
Collaborator

Thanks for opening this issue @Bin-Huang !

I realize this is not very well explained in the documentation, but ideally Viper shouldn't leave the main function.

It's also a good practice to keep your Viper setup and config unmarshaling separate. Here is a good example of that.

Lastly, I personally don't like the Get* interface, because it hints at using Viper outside of the main function. It's better to use Unmarshal and decode the config into a struct.

For these reasons, I'm not really a fond of the idea to expand the Get* interface.

I'd love to hear your thoughts about the above practices and examples and whether they would work for your use case (or if not, why).

@Bin-Huang
Copy link
Author

Your practice has helped me a lot and I think it's even better. And I also have a problem with Unmarshal which behaves confusingly with the environment. The following example can reproduce this problem:

type Conf struct {
	App struct {
		Name string
		Port int
	}
}

func main() {
	v := viper.New()
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
	v.AllowEmptyEnv(true)
	v.AutomaticEnv()

	fmt.Println(`Get`, v.GetInt("app.port")) // got 8080

	var conf Conf
	err := v.Unmarshal(&conf)
	if err != nil {
		panic(err)
	}
	fmt.Println(conf.App.Port) // expected 8080, got 0
}

When running APP_PORT=8080 go run ., I can get the correct config via methods v.Get, but always the zero value via v.Unmarshal.

As for a reason, I found that v.Unmarshal only decodes keys and settings inside the viper instance, but doesn't read from the os environment (just like v.Get). https://github.com/spf13/viper/blob/master/viper.go#L2046

Is this behavior by design? Looking forward to your suggestions and answers. 😁

@sagikazarmark
Copy link
Collaborator

Yeah, unfortunately this is a known issue: #761

The workaround is either manually binding the env var or setting a default. It's actually probably a good idea that accepted env vars are explicitly defined somehow. I always thought that automatic env makes things a bit weird, because you never know what env vars you can use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
kind/enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants