github.com/annwntech/go-micro/v2@v2.9.5/codec/json/marshaler.go (about) 1 package json 2 3 import ( 4 "bytes" 5 "encoding/json" 6 7 "github.com/golang/protobuf/jsonpb" 8 "github.com/golang/protobuf/proto" 9 "github.com/oxtoacart/bpool" 10 ) 11 12 var jsonpbMarshaler = &jsonpb.Marshaler{} 13 14 // create buffer pool with 16 instances each preallocated with 256 bytes 15 var bufferPool = bpool.NewSizedBufferPool(16, 256) 16 17 type Marshaler struct{} 18 19 func (j Marshaler) Marshal(v interface{}) ([]byte, error) { 20 if pb, ok := v.(proto.Message); ok { 21 buf := bufferPool.Get() 22 defer bufferPool.Put(buf) 23 if err := jsonpbMarshaler.Marshal(buf, pb); err != nil { 24 return nil, err 25 } 26 return buf.Bytes(), nil 27 } 28 return json.Marshal(v) 29 } 30 31 func (j Marshaler) Unmarshal(d []byte, v interface{}) error { 32 if pb, ok := v.(proto.Message); ok { 33 return jsonpb.Unmarshal(bytes.NewReader(d), pb) 34 } 35 return json.Unmarshal(d, v) 36 } 37 38 func (j Marshaler) String() string { 39 return "json" 40 }