2019-06-03 18:44:43 +01:00
|
|
|
package grpc
|
|
|
|
|
|
|
|
import (
|
2021-10-27 00:57:12 +03:00
|
|
|
"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
|
|
|
)
|
|
|
|
|
2021-09-27 09:06:52 +03:00
|
|
|
var (
|
|
|
|
_ encoding.Codec = &wrapMicroCodec{}
|
|
|
|
_ codec.Codec = &wrapGrpcCodec{}
|
|
|
|
)
|
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
type wrapStream struct{ grpc.ClientStream }
|
2019-06-03 18:44:43 +01:00
|
|
|
|
2020-11-26 01:18:35 +03: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
|
|
|
}
|
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
func (w *wrapStream) Read(d []byte) (int, error) {
|
|
|
|
m := &codec.Frame{}
|
|
|
|
err := w.ClientStream.RecvMsg(m)
|
2021-07-31 15:10:59 +03:00
|
|
|
copy(d, m.Data)
|
2020-11-26 01:18:35 +03:00
|
|
|
return len(d), err
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
type wrapMicroCodec struct{ codec.Codec }
|
2019-06-03 18:44:43 +01:00
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
func (w *wrapMicroCodec) Name() string {
|
|
|
|
return w.Codec.String()
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
2021-09-27 09:06:52 +03: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)
|
|
|
|
}
|
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
type wrapGrpcCodec struct{ encoding.Codec }
|
2019-06-03 18:44:43 +01:00
|
|
|
|
2020-11-26 01:18:35 +03:00
|
|
|
func (w *wrapGrpcCodec) String() string {
|
|
|
|
return w.Codec.Name()
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
2021-09-27 09:06:52 +03:00
|
|
|
func (w *wrapGrpcCodec) Marshal(v interface{}, opts ...codec.Option) ([]byte, error) {
|
2021-04-26 19:17:29 +03:00
|
|
|
if m, ok := v.(*codec.Frame); ok {
|
2020-09-18 18:27:29 +03:00
|
|
|
return m.Data, nil
|
2020-04-08 12:50:19 +03:00
|
|
|
}
|
2020-11-26 01:18:35 +03:00
|
|
|
return w.Codec.Marshal(v)
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|
|
|
|
|
2021-09-27 09:06:52 +03:00
|
|
|
func (w *wrapGrpcCodec) Unmarshal(d []byte, v interface{}, opts ...codec.Option) error {
|
2020-11-26 01:18:35 +03:00
|
|
|
if d == nil || v == nil {
|
2020-03-10 15:21:43 +00:00
|
|
|
return nil
|
|
|
|
}
|
2021-04-26 19:17:29 +03:00
|
|
|
if m, ok := v.(*codec.Frame); ok {
|
2020-11-26 01:18:35 +03:00
|
|
|
m.Data = d
|
2020-09-18 18:27:29 +03:00
|
|
|
return nil
|
2019-07-04 16:43:36 +08:00
|
|
|
}
|
2020-11-26 01:18:35 +03:00
|
|
|
return w.Codec.Unmarshal(d, v)
|
2019-06-03 18:44:43 +01:00
|
|
|
}
|