From 0a1666a81f326ef6acc554314b96b54e40b95525 Mon Sep 17 00:00:00 2001 From: Tom Wambold Date: Mon, 19 Nov 2018 10:29:38 -0500 Subject: [PATCH] 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. --- marshal.go | 7 ++++++- marshal_test.go | 17 +++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/marshal.go b/marshal.go index b6e8ec1..3e92a57 100644 --- a/marshal.go +++ b/marshal.go @@ -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 { diff --git a/marshal_test.go b/marshal_test.go index 8d00322..9c401b3 100644 --- a/marshal_test.go +++ b/marshal_test.go @@ -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") + } +}