github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/proto/proto.go (about) 1 // Licensed under the Apache License, Version 2.0 (the "License"); 2 // you may not use this file except in compliance with the License. 3 // You may obtain a copy of the License at 4 // 5 // https://www.apache.org/licenses/LICENSE-2.0 6 // 7 // Unless required by applicable law or agreed to in writing, software 8 // distributed under the License is distributed on an "AS IS" BASIS, 9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 // See the License for the specific language governing permissions and 11 // limitations under the License. 12 // 13 // Original source: github.com/micro/go-micro/v3/codec/proto/proto.go 14 15 // Package proto provides a proto codec 16 package proto 17 18 import ( 19 "io" 20 "io/ioutil" 21 22 "github.com/golang/protobuf/proto" 23 "github.com/tickoalcantara12/micro/v3/util/codec" 24 ) 25 26 type Codec struct { 27 Conn io.ReadWriteCloser 28 } 29 30 func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error { 31 return nil 32 } 33 34 func (c *Codec) ReadBody(b interface{}) error { 35 if b == nil { 36 return nil 37 } 38 buf, err := ioutil.ReadAll(c.Conn) 39 if err != nil { 40 return err 41 } 42 m, ok := b.(proto.Message) 43 if !ok { 44 return codec.ErrInvalidMessage 45 } 46 return proto.Unmarshal(buf, m) 47 } 48 49 func (c *Codec) Write(m *codec.Message, b interface{}) error { 50 if b == nil { 51 // Nothing to write 52 return nil 53 } 54 p, ok := b.(proto.Message) 55 if !ok { 56 return codec.ErrInvalidMessage 57 } 58 buf, err := proto.Marshal(p) 59 if err != nil { 60 return err 61 } 62 _, err = c.Conn.Write(buf) 63 return err 64 } 65 66 func (c *Codec) Close() error { 67 return c.Conn.Close() 68 } 69 70 func (c *Codec) String() string { 71 return "proto" 72 } 73 74 func NewCodec(c io.ReadWriteCloser) codec.Codec { 75 return &Codec{ 76 Conn: c, 77 } 78 }