micro/codec/json/marshaler.go

46 lines
1.1 KiB
Go
Raw Normal View History

2019-01-10 09:42:02 +00:00
package json
import (
"bytes"
2019-01-10 09:42:02 +00:00
"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"
2019-01-10 09:42:02 +00:00
)
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)
2019-01-10 09:42:02 +00:00
type Marshaler struct{}
func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
switch m := v.(type) {
case proto.Message:
return jsonpbMarshaler.Marshal(m)
case oldproto.Message:
buf, err := oldjsonpbMarshaler.MarshalToString(m)
return []byte(buf), err
}
2019-01-10 09:42:02 +00:00
return json.Marshal(v)
}
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
switch m := v.(type) {
case proto.Message:
return jsonpb.Unmarshal(d, m)
case oldproto.Message:
return oldjsonpb.Unmarshal(bytes.NewReader(d), m)
}
2019-01-10 09:42:02 +00:00
return json.Unmarshal(d, v)
}
func (j Marshaler) String() string {
return "json"
}