Skip to content

Sub() ignores variables set with BindEnv/AutomaticEnv #507

@lucasvo

Description

@lucasvo

The following example fails because Sub() because variables overwritten in env are ignored.

grandParent:
    parent:
        child: bar
package main

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
	"strings"
)

var v *viper.Viper

func main() {
	os.Setenv("GRANDPARENT_PARENT_CHILD", "foo")
	v = viper.New()
	v.SetConfigType("yaml")
	v.AutomaticEnv()
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	f, _ := os.Open("test.yaml")
	v.ReadConfig(f)
	sub := v.Sub("grandParent.parent")
	fmt.Println("Direct", v.GetString("grandParent.parent.child"))
	fmt.Println("Sub", sub.GetString("child"))
	if sub.GetString("child") != v.GetString("grandParent.parent.child") {
		panic("sub ignores os.environ")
	}
}

The output of the program is:

Direct foo
Sub bar
panic: sub ignores os.environ
[...]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions