marshal_proto.go 1.5 KB

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