micro/codec/json/marshaler.go

41 lines
878 B
Go
Raw Normal View History

2019-01-10 12:42:02 +03:00
package json
import (
"bytes"
2019-01-10 12:42:02 +03:00
"encoding/json"
"github.com/golang/protobuf/jsonpb"
"github.com/golang/protobuf/proto"
"github.com/oxtoacart/bpool"
2019-01-10 12:42:02 +03:00
)
var jsonpbMarshaler = &jsonpb.Marshaler{}
// create buffer pool with 16 instances each preallocated with 256 bytes
var bufferPool = bpool.NewSizedBufferPool(16, 256)
2019-01-10 12:42:02 +03:00
type Marshaler struct{}
func (j Marshaler) Marshal(v interface{}) ([]byte, error) {
if pb, ok := v.(proto.Message); ok {
buf := bufferPool.Get()
defer bufferPool.Put(buf)
if err := jsonpbMarshaler.Marshal(buf, pb); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
2019-01-10 12:42:02 +03:00
return json.Marshal(v)
}
func (j Marshaler) Unmarshal(d []byte, v interface{}) error {
if pb, ok := v.(proto.Message); ok {
return jsonpb.Unmarshal(bytes.NewReader(d), pb)
}
2019-01-10 12:42:02 +03:00
return json.Unmarshal(d, v)
}
func (j Marshaler) String() string {
return "json"
}