-
Notifications
You must be signed in to change notification settings - Fork 0
/
codec.go
74 lines (54 loc) · 1.38 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
70
71
72
73
74
package protojson
import (
"bytes"
"encoding/json"
"github.com/pubgo/lava/core/encoding"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
const Name = "jsonpb"
func init() {
encoding.Register(Name, &jsonCodec{})
}
var useNumber bool
// UseNumber fix unmarshal Number(8234567890123456789) to interface(8.234567890123457e+18)
func UseNumber() {
useNumber = true
}
var (
jsonMarshaller = &protojson.MarshalOptions{EmitUnpopulated: true}
jsonUnmarshal = &protojson.UnmarshalOptions{AllowPartial: true}
)
type jsonCodec struct{}
func (j *jsonCodec) Name() string { return Name }
func (j *jsonCodec) Encode(v interface{}) ([]byte, error) {
if m, ok := v.(json.Marshaler); ok {
return m.MarshalJSON()
}
if pb, ok := v.(proto.Message); ok {
return jsonMarshaller.Marshal(pb)
}
return json.Marshal(v)
}
func (j *jsonCodec) Decode(data []byte, v interface{}) error {
if len(data) == 0 {
return nil
}
if m, ok := v.(json.Unmarshaler); ok {
return m.UnmarshalJSON(data)
}
if pb, ok := v.(proto.Message); ok {
return jsonUnmarshal.Unmarshal(data, pb)
}
dec := json.NewDecoder(bytes.NewReader(data))
if useNumber {
dec.UseNumber()
}
return dec.Decode(v)
}
func (j *jsonCodec) Marshal(v interface{}) ([]byte, error) {
return j.Encode(v)
}
func (j *jsonCodec) Unmarshal(data []byte, v interface{}) error {
return j.Decode(data, v)
}