1
0
mirror of https://github.com/go-micro/go-micro.git synced 2025-01-17 17:44:30 +02:00
go-micro/codec/proto/proto.go

64 lines
1014 B
Go
Raw Normal View History

2018-12-31 22:01:16 +00:00
// Package proto provides a proto codec
package proto
import (
"io"
2021-10-12 12:55:53 +01:00
"go-micro.dev/v4/codec"
2018-12-31 22:01:16 +00:00
"github.com/golang/protobuf/proto"
)
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 12:09:04 +00:00
if b == nil {
return nil
}
buf, err := io.ReadAll(c.Conn)
2018-12-31 22:01:16 +00:00
if err != nil {
return err
}
m, ok := b.(proto.Message)
if !ok {
return codec.ErrInvalidMessage
}
return proto.Unmarshal(buf, m)
2018-12-31 22:01:16 +00:00
}
func (c *Codec) Write(m *codec.Message, b interface{}) error {
if b == nil {
// Nothing to write
return nil
}
2019-01-08 15:38:25 +00:00
p, ok := b.(proto.Message)
if !ok {
return codec.ErrInvalidMessage
2019-01-08 15:38:25 +00:00
}
buf, err := proto.Marshal(p)
2018-12-31 22:01:16 +00: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,
}
}