Skip to content

Commit

Permalink
fix(go): item.Marshal should support defined types
Browse files Browse the repository at this point in the history
  • Loading branch information
rot1024 committed Nov 7, 2023
1 parent 343f705 commit f77ca28
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 26 deletions.
25 changes: 2 additions & 23 deletions go/model.go
Original file line number Diff line number Diff line change
Expand Up @@ -285,32 +285,11 @@ func (d *Item) Unmarshal(i any) {
}
}

if !vf.CanSet() {
if itf == nil || !vf.CanSet() || !reflect.TypeOf(itf.Value).AssignableTo(vf.Type()) {
continue
}

if itf != nil {
if f.Type.Kind() == reflect.String {
if itfv := itf.GetValue().String(); itfv != nil {
vf.SetString(*itfv)
}
} else if f.Type.Kind() == reflect.Slice && f.Type.Elem().Kind() == reflect.String {
if te := f.Type.Elem(); te.Name() == "string" {
if itfv := itf.GetValue().Strings(); itfv != nil {
vf.Set(reflect.ValueOf(itfv))
}
} else if itfv := itf.GetValue().Strings(); itfv != nil {
s := reflect.MakeSlice(f.Type, 0, len(itfv))
for _, v := range itfv {
rv := reflect.ValueOf(v).Convert(te)
s = reflect.Append(s, rv)
}
vf.Set(s)
}
} else if itf.Value != nil && reflect.TypeOf(itf.Value).AssignableTo(vf.Type()) {
vf.Set(reflect.ValueOf(itf.Value))
}
}
vf.Set(reflect.ValueOf(itf.Value))
}
}

Expand Down
6 changes: 3 additions & 3 deletions go/model_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,9 @@ func TestItem_Unmarshal(t *testing.T) {
(&Item{
ID: "xxx",
Fields: []*Field{
{Key: "aaa", Value: "bbb"},
{Key: "aaa", Value: str("bbb")},
{Key: "bbb", Value: []string{"ccc", "bbb"}},
{Key: "ccc", Value: []string{"a", "b"}},
{Key: "ccc", Value: []str{"a", "b"}},
{Key: "ddd", Value: map[string]any{"a": "b"}},
{Key: "ggg", Type: "group", Value: []string{"1", "2"}},
{Key: "hhh", Type: "group", Value: []string{"1"}},
Expand All @@ -73,7 +73,7 @@ func TestItem_Unmarshal(t *testing.T) {

assert.Equal(t, S{
ID: "xxx",
AAA: "bbb",
AAA: str("bbb"),
BBB: []string{"ccc", "bbb"},
CCC: []str{"a", "b"},
DDD: map[string]any{"a": "b"},
Expand Down

0 comments on commit f77ca28

Please sign in to comment.