Skip to content

Commit 99a91c6

Browse files
committed
Fix Get() panic on nil pointers. Fixes #396.
1 parent fbccb44 commit 99a91c6

2 files changed

Lines changed: 30 additions & 0 deletions

File tree

koanf.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,13 @@ func (ko *Koanf) Get(path string) any {
351351
return v
352352
case map[string]any:
353353
return maps.Copy(v)
354+
case nil:
355+
return nil
356+
}
357+
358+
// Skil nil pointers before copying.
359+
if rv := reflect.ValueOf(res); rv.Kind() == reflect.Ptr && rv.IsNil() {
360+
return nil
354361
}
355362

356363
out, _ := copystructure.Copy(&res)

tests/koanf_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2046,3 +2046,26 @@ func TestFileProviderConcurrency(t *testing.T) {
20462046
t.Fatal("FILE PROVIDER DEADLOCK: Goroutines did not complete within timeout")
20472047
}
20482048
}
2049+
2050+
// TestGetNilPointer tests Get()'ing nil pointers.
2051+
func TestGetNilPointer(t *testing.T) {
2052+
assert := assert.New(t)
2053+
k := koanf.New(".")
2054+
2055+
type test struct {
2056+
Name string
2057+
}
2058+
var nt *test
2059+
assert.Nil(k.Set("key", nt))
2060+
assert.True(k.Exists("key"))
2061+
assert.Nil(k.Get("key"))
2062+
2063+
// Test nil value.
2064+
assert.Nil(k.Set("val", nil))
2065+
assert.Nil(k.Get("val"))
2066+
2067+
// Test slice.
2068+
var s *[]string
2069+
assert.Nil(k.Set("slice", s))
2070+
assert.Nil(k.Get("slice"))
2071+
}

0 commit comments

Comments
 (0)