Skip to content

Commit 3b2e16c

Browse files
author
Jimmy Spagnola
committed
Add decodeStructFromMap for map field name.
1 parent 4bf87ce commit 3b2e16c

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

mapstructure.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1593,6 +1593,8 @@ func (d *Decoder) decodeStructFromMap(name string, dataVal, val reflect.Value) e
15931593
tagValue = strings.SplitN(tagValue, ",", 2)[0]
15941594
if tagValue != "" {
15951595
fieldName = tagValue
1596+
} else {
1597+
fieldName = d.config.MapFieldName(fieldName)
15961598
}
15971599

15981600
rawMapKey := reflect.ValueOf(fieldName)

mapstructure_test.go

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3687,7 +3687,7 @@ type TestMapFieldName struct {
36873687
Username string
36883688
}
36893689

3690-
func TestDecoder_MapFieldName(t *testing.T) {
3690+
func TestDecoder_MapFieldNameMapFromStruct(t *testing.T) {
36913691
var structKeys map[string]any
36923692

36933693
decoder, err := NewDecoder(&DecoderConfig{
@@ -3721,3 +3721,41 @@ func TestDecoder_MapFieldName(t *testing.T) {
37213721
t.Fatal("expected Username to exist")
37223722
}
37233723
}
3724+
3725+
func TestDecoder_MapFieldNameStructFromMap(t *testing.T) {
3726+
foo := TestMapFieldName{}
3727+
3728+
decoder, err := NewDecoder(&DecoderConfig{
3729+
Result: &foo,
3730+
MapFieldName: func(s string) string {
3731+
if s == "HostName" {
3732+
return "host_name"
3733+
}
3734+
if s == "Username" {
3735+
return "user_name"
3736+
}
3737+
return s
3738+
},
3739+
})
3740+
if err != nil {
3741+
t.Fatalf("err: %s", err)
3742+
}
3743+
3744+
structKeys := map[string]any{
3745+
"host_name": "foo",
3746+
"user_name": "bar",
3747+
}
3748+
3749+
err = decoder.Decode(&structKeys)
3750+
if err != nil {
3751+
t.Fatalf("err: %s", err)
3752+
}
3753+
3754+
if foo.HostName != "foo" {
3755+
t.Fatal("expected HostName to be foo")
3756+
}
3757+
3758+
if foo.Username != "bar" {
3759+
t.Fatal("expected Username to be bar")
3760+
}
3761+
}

0 commit comments

Comments
 (0)