Skip to content

Commit 9183af5

Browse files
author
Divjot Arora
committed
Change struct decoder to be case-insensitive.
GODRIVER-1011 Change-Id: I31674da7af7405f659dbbe7d0aaeeadca7fdb946
1 parent 4028be8 commit 9183af5

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

bson/bsoncodec/struct_codec.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"errors"
1111
"fmt"
1212
"reflect"
13+
"strings"
1314
"sync"
1415

1516
"go.mongodb.org/mongo-driver/bson/bsonrw"
@@ -160,6 +161,13 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val r
160161
}
161162

162163
fd, exists := sd.fm[name]
164+
if !exists {
165+
// if the original name isn't found in the struct description, try again with the name in lowercase
166+
// this could match if a BSON tag isn't specified because by default, describeStruct lowercases all field
167+
// names
168+
fd, exists = sd.fm[strings.ToLower(name)]
169+
}
170+
163171
if !exists {
164172
if sd.inlineMap < 0 {
165173
// The encoding/json package requires a flag to return on error for non-existent fields.

bson/unmarshaling_cases_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,17 @@ var unmarshalingTestCases = []unmarshalingTestCase{
6464
},
6565
docToBytes(D{{"foo", A{true}}}),
6666
},
67+
{
68+
"struct with mixed case fields",
69+
nil,
70+
reflect.TypeOf(struct {
71+
FooBar int32
72+
}{}),
73+
&struct {
74+
FooBar int32
75+
}{
76+
FooBar: 10,
77+
},
78+
docToBytes(D{{"fooBar", int32(10)}}),
79+
},
6780
}

0 commit comments

Comments
 (0)