From dabedfb38b74d175936dd0b1b256cdbc0bff09ff Mon Sep 17 00:00:00 2001 From: Menghan Li Date: Tue, 23 Feb 2021 09:47:33 -0800 Subject: [PATCH] encoding/proto: do not panic when types do not match (#4218) --- encoding/proto/proto.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/encoding/proto/proto.go b/encoding/proto/proto.go index e1230fdd358a..3009b35afe7d 100644 --- a/encoding/proto/proto.go +++ b/encoding/proto/proto.go @@ -21,6 +21,8 @@ package proto import ( + "fmt" + "github.com/golang/protobuf/proto" "google.golang.org/grpc/encoding" ) @@ -36,11 +38,19 @@ func init() { type codec struct{} func (codec) Marshal(v interface{}) ([]byte, error) { - return proto.Marshal(v.(proto.Message)) + vv, ok := v.(proto.Message) + if !ok { + return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) + } + return proto.Marshal(vv) } func (codec) Unmarshal(data []byte, v interface{}) error { - return proto.Unmarshal(data, v.(proto.Message)) + vv, ok := v.(proto.Message) + if !ok { + return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) + } + return proto.Unmarshal(data, vv) } func (codec) Name() string {