fix old proto

Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
Василий Толстов 2020-09-10 15:17:23 +03:00
parent 9ea3149b60
commit 5bfca99627

View File

@ -1,14 +1,18 @@
package json
import (
"bytes"
"encoding/json"
oldjsonpb "github.com/golang/protobuf/jsonpb"
oldproto "github.com/golang/protobuf/proto"
"github.com/oxtoacart/bpool"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var jsonpbMarshaler = &jsonpb.MarshalOptions{}
var oldjsonpbMarshaler = &oldjsonpb.Marshaler{}
// create buffer pool with 16 instances each preallocated with 256 bytes
var bufferPool = bpool.NewSizedBufferPool(16, 256)
@ -16,19 +20,22 @@ var bufferPool = bpool.NewSizedBufferPool(16, 256)
type Marshaler struct{}
func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
if pb, ok := v.(proto.Message); ok {
buf, err := jsonpbMarshaler.Marshal(pb)
if err != nil {
return nil, err
}
return buf, nil
switch m := v.(type) {
case proto.Message:
return jsonpbMarshaler.Marshal(m)
case oldproto.Message:
buf, err := oldjsonpbMarshaler.MarshalToString(m)
return []byte(buf), err
}
return json.Marshal(v)
}
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
if pb, ok := v.(proto.Message); ok {
return jsonpb.Unmarshal(d, pb)
switch m := v.(type) {
case proto.Message:
return jsonpb.Unmarshal(d, m)
case oldproto.Message:
return oldjsonpb.Unmarshal(bytes.NewReader(d), m)
}
return json.Unmarshal(d, v)
}