micro-server-grpc/codec.go

85 lines
1.7 KiB
Go
Raw Permalink Normal View History

2019-06-03 20:44:43 +03:00
package grpc
import (
"io"
2019-06-03 20:44:43 +03:00
"github.com/unistack-org/micro/v3/codec"
2019-06-18 20:51:52 +03:00
"google.golang.org/grpc"
2019-06-03 20:44:43 +03:00
"google.golang.org/grpc/encoding"
)
type wrapStream struct{ grpc.ServerStream }
2019-06-03 20:44:43 +03:00
func (w *wrapStream) Write(d []byte) (int, error) {
n := len(d)
err := w.ServerStream.SendMsg(&codec.Frame{Data: d})
return n, err
2019-06-17 22:05:58 +03:00
}
func (w *wrapStream) Read(d []byte) (int, error) {
m := &codec.Frame{}
err := w.ServerStream.RecvMsg(m)
d = m.Data
return len(d), err
2019-06-17 22:05:58 +03:00
}
type wrapMicroCodec struct{ codec.Codec }
2019-06-17 22:05:58 +03:00
func (w *wrapMicroCodec) Name() string {
return w.Codec.String()
2019-06-03 20:44:43 +03:00
}
type wrapGrpcCodec struct{ encoding.Codec }
2019-06-03 20:44:43 +03:00
func (w *wrapGrpcCodec) String() string {
return w.Codec.Name()
2019-06-03 20:44:43 +03:00
}
func (w *wrapGrpcCodec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case *codec.Frame:
return m.Data, nil
2019-06-03 20:44:43 +03:00
}
return w.Codec.Marshal(v)
2019-06-03 20:44:43 +03:00
}
func (w wrapGrpcCodec) Unmarshal(d []byte, v interface{}) error {
if d == nil || v == nil {
return nil
}
switch m := v.(type) {
case *codec.Frame:
m.Data = d
return nil
}
return w.Codec.Unmarshal(d, v)
2019-06-03 20:44:43 +03:00
}
2019-06-18 20:51:52 +03:00
func (g *wrapGrpcCodec) ReadHeader(conn io.Reader, m *codec.Message, mt codec.MessageType) error {
2019-06-18 20:51:52 +03:00
return nil
}
func (g *wrapGrpcCodec) ReadBody(conn io.Reader, v interface{}) error {
2019-06-18 20:51:52 +03:00
// caller has requested a frame
switch m := v.(type) {
case *codec.Frame:
_, err := conn.Read(m.Data)
return err
2019-06-18 20:51:52 +03:00
}
return codec.ErrInvalidMessage
2019-06-18 20:51:52 +03:00
}
func (g *wrapGrpcCodec) Write(conn io.Writer, m *codec.Message, v interface{}) error {
2019-06-18 20:51:52 +03:00
// if we don't have a body
if v != nil {
b, err := g.Marshal(v)
2019-06-18 20:51:52 +03:00
if err != nil {
return err
}
m.Body = b
}
// write the body using the framing codec
_, err := conn.Write(m.Body)
return err
2019-06-18 20:51:52 +03:00
}