From fd2335ba38c477b0c4f011a6e3bcb845b44aa53f Mon Sep 17 00:00:00 2001 From: Tony Chen Date: Sun, 3 Apr 2022 00:48:54 +0800 Subject: [PATCH] add json codec for grpc (#1908) --- transport/grpc/codec.go | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 transport/grpc/codec.go diff --git a/transport/grpc/codec.go b/transport/grpc/codec.go new file mode 100644 index 000000000..1b2c82893 --- /dev/null +++ b/transport/grpc/codec.go @@ -0,0 +1,36 @@ +package grpc + +import ( + "fmt" + + "github.com/go-kratos/kratos/v2/encoding/json" + "google.golang.org/grpc/encoding" + "google.golang.org/protobuf/proto" +) + +func init() { + encoding.RegisterCodec(codec{}) +} + +// codec is a Codec implementation with protobuf. It is the default codec for gRPC. +type codec struct{} + +func (codec) Marshal(v interface{}) ([]byte, error) { + vv, ok := v.(proto.Message) + if !ok { + return nil, fmt.Errorf("failed to marshal, message is %T, want proto.Message", v) + } + return json.MarshalOptions.Marshal(vv) +} + +func (codec) Unmarshal(data []byte, v interface{}) error { + vv, ok := v.(proto.Message) + if !ok { + return fmt.Errorf("failed to unmarshal, message is %T, want proto.Message", v) + } + return json.UnmarshalOptions.Unmarshal(data, vv) +} + +func (codec) Name() string { + return "json" +}