-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson.go
69 lines (61 loc) · 1.41 KB
/
json.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 nidhi
import (
"encoding/json"
jsoniter "github.com/json-iterator/go"
"github.com/srikrsna/protojsoniter"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
type bufferer interface {
Buffer() []byte
}
type buffer []byte
func (b buffer) Buffer() []byte { return b }
func getJson(v any) (bufferer, error) {
switch v := v.(type) {
case Metadata:
w := jsoniter.ConfigDefault.BorrowStream(nil)
v.writeJSON(w)
return w, w.Error
case protojsoniter.Writer:
w := jsoniter.ConfigDefault.BorrowStream(nil)
v.WriteJSON(w)
return w, w.Error
case proto.Message:
jsonData, err := protojson.Marshal(v)
if err != nil {
return nil, err
}
return buffer(jsonData), nil
default:
jsonData, err := json.Marshal(v)
if err != nil {
return nil, err
}
return buffer(jsonData), nil
}
}
func putJson(v bufferer) {
switch v := v.(type) {
case *jsoniter.Stream:
jsoniter.ConfigDefault.ReturnStream(v)
}
}
func unmarshalJSON(b []byte, v any) error {
switch v := v.(type) {
case Metadata:
r := jsoniter.ConfigDefault.BorrowIterator(b)
defer jsoniter.ConfigDefault.ReturnIterator(r)
v.readJSON(r)
return r.Error
case protojsoniter.Reader:
r := jsoniter.ConfigDefault.BorrowIterator(b)
defer jsoniter.ConfigDefault.ReturnIterator(r)
v.ReadJSON(r)
return r.Error
case proto.Message:
return protojson.Unmarshal(b, v)
default:
return json.Unmarshal(b, v)
}
}