fix codec.Frame in case of flatten struct tag

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2021-09-24 00:00:41 +03:00
parent 0249d6a441
commit 4615b86fb5
2 changed files with 41 additions and 9 deletions

View File

@ -3,8 +3,40 @@ package json
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 `json:"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 TestStructByTag(t *testing.T) { func TestStructByTag(t *testing.T) {
type Str struct { type Str struct {
Name []string `json:"name" codec:"flatten"` Name []string `json:"name" codec:"flatten"`

18
json.go
View File

@ -43,10 +43,6 @@ func (c *jsonCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error)
return nil, nil return nil, nil
} }
if m, ok := v.(*codec.Frame); ok {
return m.Data, nil
}
options := c.opts options := c.opts
for _, o := range opts { for _, o := range opts {
o(&options) o(&options)
@ -56,6 +52,10 @@ func (c *jsonCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error)
v = nv v = nv
} }
if m, ok := v.(*codec.Frame); ok {
return m.Data, nil
}
marshalOptions := DefaultMarshalOptions marshalOptions := DefaultMarshalOptions
if options.Context != nil { if options.Context != nil {
if f, ok := options.Context.Value(marshalOptionsKey{}).(JsonMarshalOptions); ok { if f, ok := options.Context.Value(marshalOptionsKey{}).(JsonMarshalOptions); ok {
@ -80,11 +80,6 @@ func (c *jsonCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) err
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)
@ -94,6 +89,11 @@ func (c *jsonCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) err
v = nv v = nv
} }
if m, ok := v.(*codec.Frame); ok {
m.Data = b
return nil
}
unmarshalOptions := DefaultUnmarshalOptions unmarshalOptions := DefaultUnmarshalOptions
if options.Context != nil { if options.Context != nil {
if f, ok := options.Context.Value(unmarshalOptionsKey{}).(JsonUnmarshalOptions); ok { if f, ok := options.Context.Value(unmarshalOptionsKey{}).(JsonUnmarshalOptions); ok {