github.com/annwntech/go-micro/v2@v2.9.5/codec/text/text.go (about) 1 // Package text reads any text/* content-type 2 package text 3 4 import ( 5 "fmt" 6 "io" 7 "io/ioutil" 8 9 "github.com/annwntech/go-micro/v2/codec" 10 ) 11 12 type Codec struct { 13 Conn io.ReadWriteCloser 14 } 15 16 // Frame gives us the ability to define raw data to send over the pipes 17 type Frame struct { 18 Data []byte 19 } 20 21 func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error { 22 return nil 23 } 24 25 func (c *Codec) ReadBody(b interface{}) error { 26 // read bytes 27 buf, err := ioutil.ReadAll(c.Conn) 28 if err != nil { 29 return err 30 } 31 32 switch v := b.(type) { 33 case *string: 34 *v = string(buf) 35 case *[]byte: 36 *v = buf 37 case *Frame: 38 v.Data = buf 39 default: 40 return fmt.Errorf("failed to read body: %v is not type of *[]byte", b) 41 } 42 43 return nil 44 } 45 46 func (c *Codec) Write(m *codec.Message, b interface{}) error { 47 var v []byte 48 switch ve := b.(type) { 49 case *Frame: 50 v = ve.Data 51 case *[]byte: 52 v = *ve 53 case *string: 54 v = []byte(*ve) 55 case string: 56 v = []byte(ve) 57 case []byte: 58 v = ve 59 default: 60 return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b) 61 } 62 _, err := c.Conn.Write(v) 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 "text" 72 } 73 74 func NewCodec(c io.ReadWriteCloser) codec.Codec { 75 return &Codec{ 76 Conn: c, 77 } 78 }