From bc6c9948c8302252a314f8f9d23431434e5d255b Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Wed, 6 May 2015 17:41:32 +0300 Subject: [PATCH] structs: fix custom tag names for nested structs --- structs.go | 4 +++- structs_test.go | 26 ++++++++++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/structs.go b/structs.go index 1c1f68b..a0b77e6 100644 --- a/structs.go +++ b/structs.go @@ -92,7 +92,9 @@ func (s *Struct) Map() map[string]interface{} { if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { // look out for embedded structs, and convert them to a // map[string]interface{} too - finalVal = Map(val.Interface()) + n := New(val.Interface()) + n.TagName = s.TagName + finalVal = n.Map() } else { finalVal = val.Interface() } diff --git a/structs_test.go b/structs_test.go index 8326176..14e3de7 100644 --- a/structs_test.go +++ b/structs_test.go @@ -115,17 +115,21 @@ func TestMap_Tag(t *testing.T) { func TestMap_CustomTag(t *testing.T) { var T = struct { - A string `dd:"x"` - B int `dd:"y"` - C bool `dd:"z"` + A string `json:"x"` + B int `json:"y"` + C bool `json:"z"` + D struct { + E string `json:"jkl"` + } `json:"nested"` }{ A: "a-value", B: 2, C: true, } + T.D.E = "e-value" s := New(T) - s.TagName = "dd" + s.TagName = "json" a := s.Map() @@ -144,6 +148,20 @@ func TestMap_CustomTag(t *testing.T) { } } + nested, ok := a["nested"].(map[string]interface{}) + if !ok { + t.Fatalf("Map should contain the D field that is tagged as 'nested'") + } + + e, ok := nested["jkl"].(string) + if !ok { + t.Fatalf("Map should contain the D.E field that is tagged as 'jkl'") + } + + if e != "e-value" { + t.Errorf("D.E field should be equal to 'e-value', got: '%v'", e) + } + } func TestMap_MultipleCustomTag(t *testing.T) {