From 4615b86fb5c0b85227240867bfd1fb7fab73c57a Mon Sep 17 00:00:00 2001 From: Vasiliy Tolstov Date: Fri, 24 Sep 2021 00:00:41 +0300 Subject: [PATCH] fix codec.Frame in case of flatten struct tag Signed-off-by: Vasiliy Tolstov --- codec_test.go | 32 ++++++++++++++++++++++++++++++++ json.go | 18 +++++++++--------- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/codec_test.go b/codec_test.go index 55a67fc..9c35174 100644 --- a/codec_test.go +++ b/codec_test.go @@ -3,8 +3,40 @@ package json import ( "bytes" "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) { type Str struct { Name []string `json:"name" codec:"flatten"` diff --git a/json.go b/json.go index d56cd09..2123425 100644 --- a/json.go +++ b/json.go @@ -43,10 +43,6 @@ func (c *jsonCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) return nil, nil } - if m, ok := v.(*codec.Frame); ok { - return m.Data, nil - } - options := c.opts for _, o := range opts { o(&options) @@ -56,6 +52,10 @@ func (c *jsonCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) v = nv } + if m, ok := v.(*codec.Frame); ok { + return m.Data, nil + } + marshalOptions := DefaultMarshalOptions if options.Context != nil { 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 } - if m, ok := v.(*codec.Frame); ok { - m.Data = b - return nil - } - options := c.opts for _, o := range opts { o(&options) @@ -94,6 +89,11 @@ func (c *jsonCodec) Unmarshal(b []byte, v interface{}, opts ...codec.Option) err v = nv } + if m, ok := v.(*codec.Frame); ok { + m.Data = b + return nil + } + unmarshalOptions := DefaultUnmarshalOptions if options.Context != nil { if f, ok := options.Context.Value(unmarshalOptionsKey{}).(JsonUnmarshalOptions); ok {