Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unmarshal doesn't work with AutomaticEnv #522

Closed
natefinch opened this issue Jun 29, 2018 · 2 comments
Closed

Unmarshal doesn't work with AutomaticEnv #522

natefinch opened this issue Jun 29, 2018 · 2 comments

Comments

@natefinch
Copy link
Contributor

At the bottom is a test that I would expect to pass, it doesn't. The crux seem to be that with AutomaticEnv, viper.Get does some magic to call into the environment, but that magic is not used during Unmarhsal, so unless you explicitly call BindEnv, the respective environment variables aren't queried.

package config

import (
	"os"
	"strings"
	"testing"

	"github.com/spf13/viper"
)

func TestViperUnmarshalAutoEnv(t *testing.T) {
	type config struct {
		Name string
	}

	name := "foobar"
	if err := os.Setenv("VIPERTEST_NAME", name); err != nil {
		t.Fatal(err)
	}

	v := viper.New()
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
	v.SetEnvPrefix("VIPERTEST")
	v.AutomaticEnv()

	// if you uncomment this line, the test will pass, otherwise it'll fail.
	// I would not expect to have to call bind if I'm using AutomaticEnv.
	// v.BindEnv("name")

	c := config{}
	if err := v.Unmarshal(&c); err != nil {
		t.Fatal(err)
	}

	if v.GetString("name") != c.Name {
		t.Fatalf("expected name to be %q but got %q", v.GetString("name"), c.Name)
	}
}
@natefinch
Copy link
Contributor Author

This looks to be a duplicate of #188

I think it's pretty clear that if someone calls viper.AutomaticEnv() and then calls Unmarshal, they expect everything in the target value to query the environment. That's what automatic means.

@YAOHAO9
Copy link

YAOHAO9 commented Oct 10, 2020

In my case:

  • It is working for windows
// 读取环境变量
viper.AutomaticEnv()
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
  • It is working for both windows and linux
for _, key := range viper.AllKeys() {
	viper.BindEnv(key, strings.ReplaceAll(key, ".", "_"))
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants