Skip to content

Silently lost defaults when invalid hierarchy is used #2067

@stefanb

Description

@stefanb

Preflight Checklist

  • I have searched the issue tracker for an issue that matches the one I want to file, without success.
  • I am not looking for support or already pursued the available support channels without success.
  • I have checked the troubleshooting guide for my problem, without success.

Viper Version

1.20.1

Go Version

1.25.1, 1.24.7

Config Source

Environment variables

Format

Other (specify below)

Repl.it link

No response

Code reproducing the issue

package main

import (
	"github.com/spf13/viper"
)

func main() {
	viper.SetDefault("setting.a", "foo")
	viper.SetDefault("setting.a.detail", "bar")

	viper.AutomaticEnv()

	println("Parsed values:")
	println("setting.a:", viper.GetString("setting.a"))
	println("setting.a.detail:", viper.GetString("setting.a.detail"))
}

Expected Behavior

Either

  • An error when default with ambiguous structure are defined or
  • Printing both values as they are valid if read from environmetn variables:
    Parsed values:
    setting.a: foo
    setting.a.detail: bar
    

Actual Behavior

One of the default values is silently lost.

The test code prints

Parsed values:
setting.a: 
setting.a.detail: bar

Steps To Reproduce

Just run the example provided above.

$ go run viperlostdefault.go
Parsed values:
setting.a: 
setting.a.detail: bar

Additional Information

I know the hierarchy is invalid for yaml or json, but that can easily happen in a large project with multiple developers. The example is intentionally simplified. In such case it would be better to validate the hierarchy and raise a panic or return an error than to silently lose the defaults. If reading just the flat key/value pairs from environment the hierarchy does not matter.

Metadata

Metadata

Assignees

No one assigned

    Labels

    kind/bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions