structure: add omitnested support to values
This commit is contained in:
parent
137635f5eb
commit
eacf1a7590
@ -44,6 +44,7 @@ func Map(s interface{}) map[string]interface{} {
|
|||||||
// map[string]interface{} too
|
// map[string]interface{} too
|
||||||
finalVal = Map(val.Interface())
|
finalVal = Map(val.Interface())
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
finalVal = val.Interface()
|
finalVal = val.Interface()
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -66,9 +67,13 @@ func Values(s interface{}) []interface{} {
|
|||||||
v, fields := strctInfo(s)
|
v, fields := strctInfo(s)
|
||||||
|
|
||||||
t := make([]interface{}, 0)
|
t := make([]interface{}, 0)
|
||||||
|
|
||||||
for _, field := range fields {
|
for _, field := range fields {
|
||||||
val := v.FieldByName(field.Name)
|
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
|
// look out for embedded structs, and convert them to a
|
||||||
// []interface{} to be added to the final values slice
|
// []interface{} to be added to the final values slice
|
||||||
for _, embeddedVal := range Values(val.Interface()) {
|
for _, embeddedVal := range Values(val.Interface()) {
|
||||||
|
|||||||
@ -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) {
|
func TestValues_Nested(t *testing.T) {
|
||||||
type A struct {
|
type A struct {
|
||||||
Name string
|
Name string
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user