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