66 lines
1.3 KiB
Go
Raw Normal View History

2019-06-03 18:44:43 +01:00
package grpc
import (
"go.unistack.org/micro/v3/codec"
2019-06-17 20:05:58 +01:00
"google.golang.org/grpc"
2019-06-18 18:51:52 +01:00
"google.golang.org/grpc/encoding"
2019-06-03 18:44:43 +01:00
)
var (
_ encoding.Codec = &wrapMicroCodec{}
_ codec.Codec = &wrapGrpcCodec{}
)
type wrapStream struct{ grpc.ClientStream }
2019-06-03 18:44:43 +01:00
func (w *wrapStream) Write(d []byte) (int, error) {
n := len(d)
err := w.ClientStream.SendMsg(&codec.Frame{Data: d})
return n, err
2019-06-17 20:05:58 +01:00
}
func (w *wrapStream) Read(d []byte) (int, error) {
m := &codec.Frame{}
err := w.ClientStream.RecvMsg(m)
copy(d, m.Data)
return len(d), err
2019-06-03 18:44:43 +01:00
}
type wrapMicroCodec struct{ codec.Codec }
2019-06-03 18:44:43 +01:00
func (w *wrapMicroCodec) Name() string {
return w.Codec.String()
2019-06-03 18:44:43 +01:00
}
func (w *wrapMicroCodec) Marshal(v interface{}) ([]byte, error) {
return w.Codec.Marshal(v)
}
func (w *wrapMicroCodec) Unmarshal(d []byte, v interface{}) error {
return w.Codec.Unmarshal(d, v)
}
type wrapGrpcCodec struct{ encoding.Codec }
2019-06-03 18:44:43 +01:00
func (w *wrapGrpcCodec) String() string {
return w.Codec.Name()
2019-06-03 18:44:43 +01:00
}
func (w *wrapGrpcCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
if m, ok := v.(*codec.Frame); ok {
return m.Data, nil
}
return w.Codec.Marshal(v)
2019-06-03 18:44:43 +01:00
}
func (w *wrapGrpcCodec) Unmarshal(d []byte, v interface{}, opts ...codec.Option) error {
if d == nil || v == nil {
return nil
}
if m, ok := v.(*codec.Frame); ok {
m.Data = d
return nil
}
return w.Codec.Unmarshal(d, v)
2019-06-03 18:44:43 +01:00
}