Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions bind.go
Original file line number Diff line number Diff line change
Expand Up @@ -241,14 +241,15 @@ func bindData(destination any, data map[string][]string, tag string, dataFiles m
val.Set(reflect.MakeMap(typ))
}
for k, v := range data {
key := reflect.ValueOf(k).Convert(typ.Key())
if isElemString {
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0]))
val.SetMapIndex(key, reflect.ValueOf(v[0]))
} else if isElemInterface {
// To maintain backward compatibility, we always bind to the first string value
// and not the slice of strings when dealing with map[string]any{}
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v[0]))
val.SetMapIndex(key, reflect.ValueOf(v[0]))
} else {
val.SetMapIndex(reflect.ValueOf(k), reflect.ValueOf(v))
val.SetMapIndex(key, reflect.ValueOf(v))
}
}
return nil
Expand Down
20 changes: 20 additions & 0 deletions bind_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,26 @@ func TestDefaultBinder_bindDataToMap(t *testing.T) {
})
}

func TestBindDataToMapWithNamedStringKey(t *testing.T) {
type key string
data := map[string][]string{"name": {"first", "second"}}
t.Run("string values", func(t *testing.T) {
var dest map[key]string
assert.NoError(t, bindData(&dest, data, "query", nil))
assert.Equal(t, map[key]string{"name": "first"}, dest)
})
t.Run("slice values", func(t *testing.T) {
var dest map[key][]string
assert.NoError(t, bindData(&dest, data, "query", nil))
assert.Equal(t, map[key][]string{"name": {"first", "second"}}, dest)
})
t.Run("interface values", func(t *testing.T) {
var dest map[key]any
assert.NoError(t, bindData(&dest, data, "query", nil))
assert.Equal(t, map[key]any{"name": "first"}, dest)
})
}

func TestBindbindData(t *testing.T) {
ts := new(bindTestStruct)
err := bindData(ts, values, "form", nil)
Expand Down