kkyr/fig

Defalut values are not applied

Closed this issue · 6 comments

Default values are not being applied if the config file does not exist

kkyr commented

Can you provide some sample code? The following is working as expected:

type Config struct {
	Database struct {
		Host string `default:"localhost"`
	}
}

func main() {
	var cfg Config
	_ = fig.Load(&cfg, fig.IgnoreFile())

	fmt.Println(cfg.Database.Host)
	// localhost
}

The code is exactly like you provided, but without "fig.IgnoreFile()". The desired behavior is to use the defaults when there is no file and to use values from the file when it exists

kkyr commented

The failure when a configuration file is absent is intentional, as this situation can indicate a genuine issue in applications, such as the deployment phase not copying over the configuration file correctly.

The IgnoreFile() option exists to cater to scenarios where the absence of a configuration file isn't problematic. Combining these behaviours could lead to ambiguity and reduce flexibility.

As a possible solution, you can manage this within your application code. If fig.Load() results in an ErrFileNotFound error, you could create a config file and then execute Load() once more. I acknowledge it's not great, but it'll get you where you want. If you have any ideas for addressing this within fig, while still aligning with the points I've previously mentioned, I'd be interested to hear them.

A lot of software I know behaves exactly as I described. If there is no config, it doesn't create a new one, but just uses the default values.

I understand it could lead to misconfiguration issues for some people, that is why you have ErrFileNotFound error. If this error is ignored that means the developer understand the risks and wants it to behave normally which includes populating the default values. Alternatively there could be a function to populate them, but it wouldn't be intuitive. When I specify default values I expect to have them if nothing else is specified.

kkyr commented

Default values are designated at the field level to offer a fallback for individual fields when specified. They do not and should not imply any behaviour for when the entire file is absent, as that is a higher-level concern.

Implementing the approach you suggest would necessitate addressing it within the Load() function's scope, e.g. as an additional Option, and then defaults at the field-level would work in either case.

kkyr commented

Closing due to inactivity.