fix: MapKeys returns empty slice for natively-typed maps
Get() preserves the concrete type of a map[string]T value loaded via Set() or a provider like structs, but MapKeys() only type-asserted map[string]any, so it silently reported no keys for anything else. Read keys via reflection instead so any map with string keys works.
This commit is contained in:
1 parent
15e76cb3d5
commit
9f860a7fd4
3 files changed
+116
-5
No files matched your search
@@ -416,13 +416,18 @@ func (ko *Koanf) MapKeys(path string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
mp, ok := o.(map[string]any)
|
||||
if !ok {
|
||||
// Not every map at a key path is loaded as map[string]any. A value
|
||||
// set directly with Set() or via a Provider such as structs keeps
|
||||
// its native map[string]T type, so the keys have to be read through
|
||||
// reflection to cover those too.
|
||||
rv := reflect.ValueOf(o)
|
||||
if rv.Kind() != reflect.Map || rv.Type().Key().Kind() != reflect.String {
|
||||
return out
|
||||
}
|
||||
out = make([]string, 0, len(mp))
|
||||
for k := range mp {
|
||||
out = append(out, k)
|
||||
|
||||
out = make([]string, 0, rv.Len())
|
||||
for _, k := range rv.MapKeys() {
|
||||
out = append(out, k.String())
|
||||
}
|
||||
sort.Strings(out)
|
||||
return out
|
||||
|
||||
Reference in new issue
Block a user