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