Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit f0483c5

Browse files
committedJun 26, 2024··
fix: apply envPrefix to all BindEnv vars
1 parent e71d7bf commit f0483c5

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed
 

‎viper.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -1106,7 +1106,11 @@ func (v *Viper) BindEnv(input ...string) error {
11061106
if len(input) == 1 {
11071107
v.env[key] = append(v.env[key], v.mergeWithEnvPrefix(key))
11081108
} else {
1109-
v.env[key] = append(v.env[key], input[1:]...)
1109+
envKeys := make([]string, len(input[:1]))
1110+
for i, envKey := range input[1:] {
1111+
envKeys[i] = v.mergeWithEnvPrefix(envKey)
1112+
}
1113+
v.env[key] = append(v.env[key], envKeys...)
11101114
}
11111115

11121116
return nil

‎viper_test.go

+24
Original file line numberDiff line numberDiff line change
@@ -2590,6 +2590,30 @@ func TestFlagShadow(t *testing.T) {
25902590
assert.Equal(t, "", v.GetString("foo.bar1.bar2"))
25912591
}
25922592

2593+
func TestBindUsesEnvPrefix(t *testing.T) {
2594+
v := New()
2595+
2596+
os.Setenv("APP_FOO", "foo")
2597+
os.Setenv("APP_BAR", "bar")
2598+
2599+
v.SetEnvPrefix("APP")
2600+
v.AutomaticEnv()
2601+
v.BindEnv("foo1", "FOO")
2602+
v.BindEnv("bar1", "BAR")
2603+
2604+
assert.Equal(t, "foo", v.Get("foo1"))
2605+
assert.Equal(t, "bar", v.Get("bar1"))
2606+
2607+
type TestStruct struct {
2608+
Foo1 string `mapstructure:"foo1"`
2609+
Bar1 string `mapstructure:"bar1"`
2610+
}
2611+
var ts TestStruct
2612+
assert.NoError(t, v.Unmarshal(&ts))
2613+
assert.Equal(t, "foo", ts.Foo1)
2614+
assert.Equal(t, "bar", ts.Bar1)
2615+
}
2616+
25932617
func BenchmarkGetBool(b *testing.B) {
25942618
key := "BenchmarkGetBool"
25952619
v = New()

0 commit comments

Comments
 (0)
Please sign in to comment.