micro/codec/json/marshaler.go
Vasiliy Tolstov 67ab44593b
fix repocard issues (#21)
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2020-08-25 15:41:48 +03:00

39 lines
815 B
Go

package json
import (
"encoding/json"
"github.com/oxtoacart/bpool"
jsonpb "google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
)
var jsonpbMarshaler = &jsonpb.MarshalOptions{}
// create buffer pool with 16 instances each preallocated with 256 bytes
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
}
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)
}
return json.Unmarshal(d, v)
}
func (j Marshaler) String() string {
return "json"
}