Skip to content

UnmarshalKey / Sub only uses read config, neglects environment variables  #1012

@manuelstein

Description

@manuelstein

Description:
A structured configuration is read using ReadConfig or ReadInConfig. Subsection keys are bound to environment variables. Viper correctly updates its config, i.e. key access Get / AllSettings works correctly. But when trying to use Unmarshal, only the config file seems to be used.

Code:

package main

import (
	"bytes"
	"fmt"
	"os"

	"github.com/spf13/viper"
)

func main() {
	v := viper.New()

	type Foo struct {
		Bar string `mapstructure:"bar"`
	}
	foo := Foo{
		Bar: "A",
	}
	var yamlExample = []byte(`
foo:
  bar: "B"
`)
	// Read config
	fmt.Println("Reading config")
	v.SetConfigType("yaml")
	v.ReadConfig(bytes.NewBuffer(yamlExample))
	fmt.Printf("%#v\n\n", v.AllSettings())

	// BindEnv
	fmt.Println("Setting env")
	os.Setenv("FOO_BAR", "C")
	v.BindEnv("foo.bar", "FOO_BAR")
	fmt.Printf("%#v\n\n", v.AllSettings())

	fmt.Println("Unmarshal")
	if err := v.Sub("foo").Unmarshal(&foo); err != nil {
		panic(err)
	}
	fmt.Printf("%#v\n\n", foo)
}

Output:

Reading config
map[string]interface {}{"foo":map[string]interface {}{"bar":"B"}}

Setting env
map[string]interface {}{"foo":map[string]interface {}{"bar":"C"}}

Unmarshal
main.Foo{Bar:"B"}

Expected Output:

...
Unmarshal
main.Foo{Bar:"C"}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions