From eacf1a759041640bdcca8670cd066684a0335698 Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Thu, 7 Aug 2014 21:57:51 +0300 Subject: [PATCH] structure: add omitnested support to values --- structure.go | 7 ++++++- structure_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/structure.go b/structure.go index 5200e23..c4174fc 100644 --- a/structure.go +++ b/structure.go @@ -44,6 +44,7 @@ func Map(s interface{}) map[string]interface{} { // map[string]interface{} too finalVal = Map(val.Interface()) } else { + finalVal = val.Interface() } @@ -66,9 +67,13 @@ func Values(s interface{}) []interface{} { v, fields := strctInfo(s) t := make([]interface{}, 0) + for _, field := range fields { val := v.FieldByName(field.Name) - if IsStruct(val.Interface()) { + + _, tagOpts := parseTag(field.Tag.Get(DefaultTagName)) + + if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { // look out for embedded structs, and convert them to a // []interface{} to be added to the final values slice for _, embeddedVal := range Values(val.Interface()) { diff --git a/structure_test.go b/structure_test.go index 0ea3946..1ab8e7e 100644 --- a/structure_test.go +++ b/structure_test.go @@ -278,6 +278,45 @@ func TestValues(t *testing.T) { } } +func TestValues_OmitNested(t *testing.T) { + type A struct { + Name string + Value int + } + + a := A{ + Name: "example", + Value: 123, + } + + type B struct { + A A `structure:",omitnested"` + C int + } + b := &B{A: a, C: 123} + + s := Values(b) + + if len(s) != 2 { + t.Errorf("Values of omitted nested struct should be not counted") + } + + inSlice := func(val interface{}) bool { + for _, v := range s { + if reflect.DeepEqual(v, val) { + return true + } + } + return false + } + + for _, val := range []interface{}{123, a} { + if !inSlice(val) { + t.Errorf("Values should have the value %v", val) + } + } +} + func TestValues_Nested(t *testing.T) { type A struct { Name string