update codec

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-11-24 16:28:10 +03:00
parent 37dcea29f7
commit 322b8cee45

57
json.go
View File

@ -4,11 +4,36 @@ package json
import ( import (
"encoding/json" "encoding/json"
"io" "io"
"io/ioutil"
"github.com/unistack-org/micro/v3/codec" "github.com/unistack-org/micro/v3/codec"
) )
type jsonCodec struct { type jsonCodec struct{}
func (c *jsonCodec) Marshal(b interface{}) ([]byte, error) {
if b == nil {
return nil, nil
}
switch m := b.(type) {
case *codec.Frame:
return m.Data, nil
}
return json.Marshal(b)
}
func (c *jsonCodec) Unmarshal(b []byte, v interface{}) error {
if b == nil {
return nil
}
switch m := v.(type) {
case *codec.Frame:
m.Data = b
return nil
}
return json.Unmarshal(b, v)
} }
func (c *jsonCodec) ReadHeader(conn io.ReadWriter, m *codec.Message, t codec.MessageType) error { func (c *jsonCodec) ReadHeader(conn io.ReadWriter, m *codec.Message, t codec.MessageType) error {
@ -19,6 +44,16 @@ func (c *jsonCodec) ReadBody(conn io.ReadWriter, b interface{}) error {
if b == nil { if b == nil {
return nil return nil
} }
switch m := b.(type) {
case *codec.Frame:
buf, err := ioutil.ReadAll(conn)
if err != nil {
return err
}
m.Data = buf
return nil
}
return json.NewDecoder(conn).Decode(b) return json.NewDecoder(conn).Decode(b)
} }
@ -26,23 +61,15 @@ func (c *jsonCodec) Write(conn io.ReadWriter, m *codec.Message, b interface{}) e
if b == nil { if b == nil {
return nil return nil
} }
switch m := b.(type) {
case *codec.Frame:
_, err := conn.Write(m.Data)
return err
}
return json.NewEncoder(conn).Encode(b) return json.NewEncoder(conn).Encode(b)
} }
func (c *jsonCodec) Marshal(b interface{}) ([]byte, error) {
if b == nil {
return nil, nil
}
return json.Marshal(b)
}
func (c *jsonCodec) Unmarshal(b []byte, v interface{}) error {
if b == nil {
return nil
}
return json.Unmarshal(b, v)
}
func (c *jsonCodec) String() string { func (c *jsonCodec) String() string {
return "json" return "json"
} }