diff --git a/viper.go b/viper.go index c3130c2..8889f87 100644 --- a/viper.go +++ b/viper.go @@ -992,6 +992,9 @@ func (v *Viper) BindPFlags(flags *pflag.FlagSet) error { func BindPFlag(key string, flag *pflag.Flag) error { return v.BindPFlag(key, flag) } func (v *Viper) BindPFlag(key string, flag *pflag.Flag) error { + if flag == nil { + return fmt.Errorf("flag for %q is nil", key) + } return v.BindFlagValue(key, pflagValue{flag}) } diff --git a/viper_test.go b/viper_test.go index 09d5021..c38c665 100644 --- a/viper_test.go +++ b/viper_test.go @@ -970,6 +970,11 @@ func TestBindPFlag(t *testing.T) { assert.Equal(t, "testing_mutate", Get("testvalue")) } +func TestBindPFlagDetectNilFlag(t *testing.T) { + result := BindPFlag("testvalue", nil) + assert.Error(t, result) +} + func TestBindPFlagStringToString(t *testing.T) { tests := []struct { Expected map[string]string