1
0
mirror of https://github.com/go-micro/go-micro.git synced 2024-12-18 08:26:38 +02:00
go-micro/codec/proto/proto.go

57 lines
913 B
Go
Raw Normal View History

2019-01-01 00:01:16 +02:00
// Package proto provides a proto codec
package proto
import (
"io"
"io/ioutil"
"github.com/golang/protobuf/proto"
"github.com/micro/go-micro/v2/codec"
2019-01-01 00:01:16 +02: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 14:09:04 +02:00
if b == nil {
return nil
}
2019-01-01 00:01:16 +02:00
buf, err := ioutil.ReadAll(c.Conn)
if err != nil {
return err
}
return proto.Unmarshal(buf, b.(proto.Message))
}
func (c *Codec) Write(m *codec.Message, b interface{}) error {
2019-01-08 17:38:25 +02:00
p, ok := b.(proto.Message)
if !ok {
return nil
}
buf, err := proto.Marshal(p)
2019-01-01 00:01:16 +02: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,
}
}