Skip to content

Commit deaa1f7

Browse files
committed
add support for struct entities in MakeVariant
currently, structs are not parsed properly since `format()` has no handling for the reflect type add a switch case to handle structs and encode some sane defaults if given an empty one resolves #328 Signed-off-by: Charlie Doern <[email protected]>
1 parent a37d5dd commit deaa1f7

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

variant.go

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ func (v Variant) format() (string, bool) {
7373
}
7474
rv := reflect.ValueOf(v.value)
7575
switch rv.Kind() {
76-
case reflect.Slice:
76+
case reflect.Slice, reflect.Array:
7777
if rv.Len() == 0 {
7878
return "[]", false
7979
}
@@ -119,6 +119,23 @@ func (v Variant) format() (string, bool) {
119119
}
120120
buf.WriteByte('}')
121121
return buf.String(), unamb
122+
case reflect.Struct:
123+
if rv.NumField() == 0 {
124+
return "{}", false
125+
}
126+
unamb := true
127+
var buf bytes.Buffer
128+
buf.WriteString("{")
129+
kvs := make([]string, rv.NumField())
130+
for i := 0; i < rv.NumField(); i++ {
131+
s, b := MakeVariant(rv.Field(i).Interface()).format()
132+
unamb = unamb && b
133+
buf.WriteString(s)
134+
kvs[i] = buf.String()
135+
}
136+
buf.WriteString("}")
137+
return buf.String(), unamb
138+
122139
}
123140
return `"INVALID"`, true
124141
}

variant_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,16 @@ import (
55
"testing"
66
)
77

8+
type Testing struct {
9+
First string
10+
Second uint64
11+
}
12+
813
var variantFormatTests = []struct {
914
v interface{}
1015
s string
1116
}{
17+
{[]Testing{{First: "testing", Second: 123}}, "@a(st) [{\"testing\"123}]"},
1218
{int32(1), `1`},
1319
{"foo", `"foo"`},
1420
{ObjectPath("/org/foo"), `@o "/org/foo"`},

0 commit comments

Comments
 (0)