2019-01-01 01:01:16 +03:00
|
|
|
// Package proto provides a proto codec
|
|
|
|
package proto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
|
2020-08-19 17:47:17 +03:00
|
|
|
"github.com/unistack-org/micro/v3/codec"
|
2020-08-25 15:41:48 +03:00
|
|
|
"google.golang.org/protobuf/proto"
|
2019-01-01 01:01:16 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type Codec struct {
|
|
|
|
Conn io.ReadWriteCloser
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadBody(b interface{}) error {
|
2019-01-17 15:09:04 +03:00
|
|
|
if b == nil {
|
|
|
|
return nil
|
|
|
|
}
|
2019-01-01 01:01:16 +03:00
|
|
|
buf, err := ioutil.ReadAll(c.Conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-02-19 02:05:38 +03:00
|
|
|
m, ok := b.(proto.Message)
|
|
|
|
if !ok {
|
|
|
|
return codec.ErrInvalidMessage
|
|
|
|
}
|
|
|
|
return proto.Unmarshal(buf, m)
|
2019-01-01 01:01:16 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Write(m *codec.Message, b interface{}) error {
|
2020-08-06 20:51:00 +03:00
|
|
|
if b == nil {
|
|
|
|
// Nothing to write
|
|
|
|
return nil
|
|
|
|
}
|
2019-01-08 18:38:25 +03:00
|
|
|
p, ok := b.(proto.Message)
|
|
|
|
if !ok {
|
2020-02-19 02:05:38 +03:00
|
|
|
return codec.ErrInvalidMessage
|
2019-01-08 18:38:25 +03:00
|
|
|
}
|
|
|
|
buf, err := proto.Marshal(p)
|
2019-01-01 01:01:16 +03:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, err = c.Conn.Write(buf)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Close() error {
|
|
|
|
return c.Conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) String() string {
|
|
|
|
return "proto"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec(c io.ReadWriteCloser) codec.Codec {
|
|
|
|
return &Codec{
|
|
|
|
Conn: c,
|
|
|
|
}
|
|
|
|
}
|