fix flatten codec.Frame case

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-09-23 17:39:34 +03:00
parent 4fd05f2da8
commit 3ba495e1f1
2 changed files with 42 additions and 10 deletions

View File

@ -3,8 +3,40 @@ package xml
import ( import (
"bytes" "bytes"
"testing" "testing"
"github.com/unistack-org/micro/v3/codec"
) )
func TestFrame(t *testing.T) {
s := &codec.Frame{Data: []byte("test")}
buf, err := NewCodec().Marshal(s)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf, []byte(`test`)) {
t.Fatalf("bytes not equal %s != %s", buf, `test`)
}
}
func TestFrameFlatten(t *testing.T) {
s := &struct {
One string
Name *codec.Frame `xml:"name" codec:"flatten"`
}{
One: "xx",
Name: &codec.Frame{Data: []byte("test")},
}
buf, err := NewCodec().Marshal(s)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(buf, []byte(`test`)) {
t.Fatalf("bytes not equal %s != %s", buf, `test`)
}
}
func TestReadBody(t *testing.T) { func TestReadBody(t *testing.T) {
s := &struct { s := &struct {
Name string Name string

20
xml.go
View File

@ -20,22 +20,22 @@ const (
) )
func (c *xmlCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) { func (c *xmlCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
switch m := v.(type) { if v == nil {
case nil:
return nil, nil return nil, nil
case *codec.Frame:
return m.Data, nil
} }
options := c.opts options := c.opts
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
} }
if nv, nerr := rutil.StructFieldByTag(v, options.TagName, flattenTag); nerr == nil { if nv, nerr := rutil.StructFieldByTag(v, options.TagName, flattenTag); nerr == nil {
v = nv v = nv
} }
if m, ok := v.(*codec.Frame); ok {
return m.Data, nil
}
return xml.Marshal(v) return xml.Marshal(v)
} }
@ -44,11 +44,6 @@ func (c *xmlCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) erro
return nil return nil
} }
if m, ok := v.(*codec.Frame); ok {
m.Data = b
return nil
}
options := c.opts options := c.opts
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
@ -58,6 +53,11 @@ func (c *xmlCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) erro
v = nv v = nv
} }
if m, ok := v.(*codec.Frame); ok {
m.Data = b
return nil
}
return xml.Unmarshal(b, v) return xml.Unmarshal(b, v)
} }