Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 27 additions & 2 deletions pkg/commoncfg/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,14 +38,21 @@ type Loader struct {
useEnv bool
fileName string
fileFormat FileFormat

decoderConfig mapstructure.DecoderConfig
}

type Option func(*Loader)

// NewLoader creates a new config loader
// Uses config.yaml as default config file
func NewLoader(cfg any, options ...Option) *Loader {
loader := &Loader{cfg: cfg}
loader := &Loader{
cfg: cfg,
decoderConfig: mapstructure.DecoderConfig{
ErrorUnused: true,
},
}

loader.fileName = DefaultFileName
loader.fileFormat = DefaultFileFormat
Expand Down Expand Up @@ -73,6 +80,24 @@ func WithPaths(paths ...string) Option {
}
}

// DisableViperErrorUnused disable the ErrorUnused flag for viper DecoderConfig, which means that it will not return an
// error if there are unknown keys in the config file. This can be useful if you want to allow extra fields in the
// config file that are not defined in the struct, but it can also hide potential issues with the config file, so use it with caution.
func DisableViperErrorUnused() Option {
return func(l *Loader) {
l.decoderConfig.ErrorUnused = false
}
}

// EnableViperErrorUnused enable the ErrorUnused flag for viper DecoderConfig, which means that it will return an error
// if there are unknown keys in the config file. This is enabled by default, but you can use this option to explicitly
// enable it if you have disabled it before.
func EnableViperErrorUnused() Option {
return func(l *Loader) {
l.decoderConfig.ErrorUnused = false
}
}

// WithFile sets the file name and type of the config file
func WithFile(name string, extension FileFormat) Option {
return func(l *Loader) {
Expand Down Expand Up @@ -133,7 +158,7 @@ func (l *Loader) LoadConfig() error {

err = v.Unmarshal(l.cfg,
func(c *mapstructure.DecoderConfig) {
c.ErrorUnused = true // error if there are unknown keys in the config
c.ErrorUnused = l.decoderConfig.ErrorUnused // error if there are unknown keys in the config
},
)
if err != nil {
Expand Down
Loading