update codec

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-11-24 16:30:31 +03:00
parent 7355dcd5a6
commit d12d65c191

View File

@ -36,9 +36,36 @@ var (
} }
) )
type jsonpbCodec struct { type jsonpbCodec struct{}
func (c *jsonpbCodec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case *codec.Frame:
return m.Data, nil
case proto.Message:
return JsonpbMarshaler.Marshal(m)
case oldproto.Message:
buf, err := OldJsonpbMarshaler.MarshalToString(m)
return []byte(buf), err
}
return nil, codec.ErrInvalidMessage
} }
func (c *jsonpbCodec) Unmarshal(d []byte, v interface{}) error {
if d == nil {
return nil
}
switch m := v.(type) {
case *codec.Frame:
m.Data = d
return nil
case proto.Message:
return JsonpbUnmarshaler.Unmarshal(d, m)
case oldproto.Message:
return OldJsonpbUnmarshaler.Unmarshal(bytes.NewReader(d), m)
}
return codec.ErrInvalidMessage
}
func (c *jsonpbCodec) ReadHeader(conn io.ReadWriter, m *codec.Message, t codec.MessageType) error { func (c *jsonpbCodec) ReadHeader(conn io.ReadWriter, m *codec.Message, t codec.MessageType) error {
return nil return nil
} }
@ -48,6 +75,13 @@ func (c *jsonpbCodec) ReadBody(conn io.ReadWriter, b interface{}) error {
return nil return nil
} }
switch m := b.(type) { switch m := b.(type) {
case *codec.Frame:
buf, err := ioutil.ReadAll(conn)
if err != nil {
return err
}
m.Data = buf
return nil
case oldproto.Message: case oldproto.Message:
return OldJsonpbUnmarshaler.Unmarshal(conn, m) return OldJsonpbUnmarshaler.Unmarshal(conn, m)
case proto.Message: case proto.Message:
@ -65,6 +99,9 @@ func (c *jsonpbCodec) Write(conn io.ReadWriter, m *codec.Message, b interface{})
return nil return nil
} }
switch m := b.(type) { switch m := b.(type) {
case *codec.Frame:
_, err := conn.Write(m.Data)
return err
case oldproto.Message: case oldproto.Message:
return OldJsonpbMarshaler.Marshal(conn, m) return OldJsonpbMarshaler.Marshal(conn, m)
case proto.Message: case proto.Message:
@ -85,27 +122,3 @@ func (c *jsonpbCodec) String() string {
func NewCodec() codec.Codec { func NewCodec() codec.Codec {
return &jsonpbCodec{} return &jsonpbCodec{}
} }
func (c *jsonpbCodec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case proto.Message:
return JsonpbMarshaler.Marshal(m)
case oldproto.Message:
buf, err := OldJsonpbMarshaler.MarshalToString(m)
return []byte(buf), err
}
return nil, codec.ErrInvalidMessage
}
func (c *jsonpbCodec) Unmarshal(d []byte, v interface{}) error {
if d == nil {
return nil
}
switch m := v.(type) {
case proto.Message:
return JsonpbUnmarshaler.Unmarshal(d, m)
case oldproto.Message:
return OldJsonpbUnmarshaler.Unmarshal(bytes.NewReader(d), m)
}
return codec.ErrInvalidMessage
}