From b655f7f55a9052f0b8cc7db3a802f58b61eb5e03 Mon Sep 17 00:00:00 2001 From: Joe Date: Mon, 8 Jul 2019 10:32:10 +0800 Subject: [PATCH] grpc: using jsonpb.Marshaler to do Marshal, map to jsonpb.Unmarsh --- client/grpc/codec.go | 8 ++++++++ server/grpc/codec.go | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/client/grpc/codec.go b/client/grpc/codec.go index f223a55c..e7891eef 100644 --- a/client/grpc/codec.go +++ b/client/grpc/codec.go @@ -22,6 +22,8 @@ type protoCodec struct{} type bytesCodec struct{} type wrapCodec struct{ encoding.Codec } +var jsonpbMarshaler = &jsonpb.Marshaler{} + var ( defaultGRPCCodecs = map[string]encoding.Codec{ "application/json": jsonCodec{}, @@ -113,6 +115,12 @@ func (bytesCodec) Name() string { } func (jsonCodec) Marshal(v interface{}) ([]byte, error) { + if pb, ok := v.(proto.Message); ok { + s, err := jsonpbMarshaler.MarshalToString(pb) + + return []byte(s), err + } + return json.Marshal(v) } diff --git a/server/grpc/codec.go b/server/grpc/codec.go index 7362f49c..53de36c3 100644 --- a/server/grpc/codec.go +++ b/server/grpc/codec.go @@ -23,6 +23,8 @@ type bytesCodec struct{} type protoCodec struct{} type wrapCodec struct{ encoding.Codec } +var jsonpbMarshaler = &jsonpb.Marshaler{} + var ( defaultGRPCCodecs = map[string]encoding.Codec{ "application/json": jsonCodec{}, @@ -78,6 +80,12 @@ func (protoCodec) Name() string { } func (jsonCodec) Marshal(v interface{}) ([]byte, error) { + if pb, ok := v.(proto.Message); ok { + s, err := jsonpbMarshaler.MarshalToString(pb) + + return []byte(s), err + } + return json.Marshal(v) }