Map camelCased keys to fields in structs (#251)
The name for each field in a struct is used to look up a key in the TOML
tree. A few different (case-sensitive) forms of this name are tried.
Previously, the current, lower-cased, and title-cased versions of the
name are tried. This precludes camelCased keys from mapping back to
fields in structs. This change adds camelCase to the set of keys to
try.
For example, the following TOML:
fooBar = 10
Would previously *not* map to the following struct:
type Foo struct {
FooBar int
}
This change corrects this.
This commit is contained in:
committed by
Thomas Pelletier
parent
aa79e12a97
commit
0a1666a81f
+6
-1
@@ -470,7 +470,12 @@ func (d *Decoder) valueFromTree(mtype reflect.Type, tval *Tree) (reflect.Value,
|
||||
opts := tomlOptions(mtypef, an)
|
||||
if opts.include {
|
||||
baseKey := opts.name
|
||||
keysToTry := []string{baseKey, strings.ToLower(baseKey), strings.ToTitle(baseKey)}
|
||||
keysToTry := []string{
|
||||
baseKey,
|
||||
strings.ToLower(baseKey),
|
||||
strings.ToTitle(baseKey),
|
||||
strings.ToLower(string(baseKey[0])) + baseKey[1:],
|
||||
}
|
||||
for _, key := range keysToTry {
|
||||
exists := tval.Has(key)
|
||||
if !exists {
|
||||
|
||||
@@ -1120,3 +1120,20 @@ func TestUnmarshalBadDuration(t *testing.T) {
|
||||
t.Fatalf("unexpected error: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
var testCamelCaseKeyToml = []byte(`fooBar = 10`)
|
||||
|
||||
func TestUnmarshalCamelCaseKey(t *testing.T) {
|
||||
var x struct {
|
||||
FooBar int
|
||||
B int
|
||||
}
|
||||
|
||||
if err := Unmarshal(testCamelCaseKeyToml, &x); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if x.FooBar != 10 {
|
||||
t.Fatal("Did not set camelCase'd key")
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user