Skip to content

Commit

Permalink
add json codec for grpc
Browse files Browse the repository at this point in the history
  • Loading branch information
tonybase committed Apr 2, 2022
1 parent 558ef4e commit a59a7b3
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions transport/grpc/codec.go
Original file line number Diff line number Diff line change
@@ -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"
}

0 comments on commit a59a7b3

Please sign in to comment.