-
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathcodec.go
38 lines (30 loc) · 869 Bytes
/
codec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package grpc
import (
"fmt"
"google.golang.org/grpc/encoding"
"google.golang.org/protobuf/proto"
enc "github.com/go-kratos/kratos/v2/encoding"
"github.com/go-kratos/kratos/v2/encoding/json"
)
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 enc.GetCodec(json.Name).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 enc.GetCodec(json.Name).Unmarshal(data, vv)
}
func (codec) Name() string {
return json.Name
}