7 "github.com/golang/protobuf/proto"
11 // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes
12 type ProtoMarshaller struct{}
14 // ContentType always returns "application/octet-stream".
15 func (*ProtoMarshaller) ContentType() string {
16 return "application/octet-stream"
19 // Marshal marshals "value" into Proto
20 func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) {
21 message, ok := value.(proto.Message)
23 return nil, errors.New("unable to marshal non proto field")
25 return proto.Marshal(message)
28 // Unmarshal unmarshals proto "data" into "value"
29 func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error {
30 message, ok := value.(proto.Message)
32 return errors.New("unable to unmarshal non proto field")
34 return proto.Unmarshal(data, message)
37 // NewDecoder returns a Decoder which reads proto stream from "reader".
38 func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
39 return DecoderFunc(func(value interface{}) error {
40 buffer, err := ioutil.ReadAll(reader)
44 return marshaller.Unmarshal(buffer, value)
48 // NewEncoder returns an Encoder which writes proto stream into "writer".
49 func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder {
50 return EncoderFunc(func(value interface{}) error {
51 buffer, err := marshaller.Marshal(value)
55 _, err = writer.Write(buffer)