marshal_proto.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package runtime
  2. import (
  3. "io"
  4. "errors"
  5. "github.com/golang/protobuf/proto"
  6. "io/ioutil"
  7. )
  8. // ProtoMarshaller is a Marshaller which marshals/unmarshals into/from serialize proto bytes
  9. type ProtoMarshaller struct{}
  10. // ContentType always returns "application/octet-stream".
  11. func (*ProtoMarshaller) ContentType() string {
  12. return "application/octet-stream"
  13. }
  14. // Marshal marshals "value" into Proto
  15. func (*ProtoMarshaller) Marshal(value interface{}) ([]byte, error) {
  16. message, ok := value.(proto.Message)
  17. if !ok {
  18. return nil, errors.New("unable to marshal non proto field")
  19. }
  20. return proto.Marshal(message)
  21. }
  22. // Unmarshal unmarshals proto "data" into "value"
  23. func (*ProtoMarshaller) Unmarshal(data []byte, value interface{}) error {
  24. message, ok := value.(proto.Message)
  25. if !ok {
  26. return errors.New("unable to unmarshal non proto field")
  27. }
  28. return proto.Unmarshal(data, message)
  29. }
  30. // NewDecoder returns a Decoder which reads proto stream from "reader".
  31. func (marshaller *ProtoMarshaller) NewDecoder(reader io.Reader) Decoder {
  32. return DecoderFunc(func(value interface{}) error {
  33. buffer, err := ioutil.ReadAll(reader)
  34. if err != nil {
  35. return err
  36. }
  37. return marshaller.Unmarshal(buffer, value)
  38. })
  39. }
  40. // NewEncoder returns an Encoder which writes proto stream into "writer".
  41. func (marshaller *ProtoMarshaller) NewEncoder(writer io.Writer) Encoder {
  42. return EncoderFunc(func(value interface{}) error {
  43. buffer, err := marshaller.Marshal(value)
  44. if err != nil {
  45. return err
  46. }
  47. _, err = writer.Write(buffer)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. })
  53. }