-
Notifications
You must be signed in to change notification settings - Fork 3
/
codec.go
69 lines (61 loc) · 1.5 KB
/
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package kratosKit
import (
"encoding/json"
"github.com/richelieu-yang/chimera/v2/src/json/jsonKit"
"reflect"
"github.com/go-kratos/kratos/v2/encoding"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
// RegisterDefaultCodec
/*
参考: 序列化 https://go-kratos.dev/docs/component/encoding
*/
func RegisterDefaultCodec() {
var p encoding.Codec = &codec{}
encoding.RegisterCodec(p)
}
var (
// marshalOptions is a configurable JSON format marshaller.
marshalOptions = protojson.MarshalOptions{
EmitUnpopulated: true,
}
// unmarshalOptions is a configurable JSON format parser.
unmarshalOptions = protojson.UnmarshalOptions{
DiscardUnknown: true,
}
)
type codec struct{}
func (*codec) Name() string {
return "json"
}
func (*codec) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case json.Marshaler:
return m.MarshalJSON()
case proto.Message:
return marshalOptions.Marshal(m)
default:
return jsonKit.Marshal(m)
}
}
func (*codec) Unmarshal(data []byte, v interface{}) error {
switch m := v.(type) {
case json.Unmarshaler:
return m.UnmarshalJSON(data)
case proto.Message:
return unmarshalOptions.Unmarshal(data, m)
default:
rv := reflect.ValueOf(v)
for rv := rv; rv.Kind() == reflect.Ptr; {
if rv.IsNil() {
rv.Set(reflect.New(rv.Type().Elem()))
}
rv = rv.Elem()
}
if m, ok := reflect.Indirect(rv).Interface().(proto.Message); ok {
return unmarshalOptions.Unmarshal(data, m)
}
return jsonKit.Unmarshal(data, m)
}
}