github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/text/text.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/text/text.go 14 15 // Package text reads any text/* content-type 16 package text 17 18 import ( 19 "fmt" 20 "io" 21 "io/ioutil" 22 23 "github.com/tickoalcantara12/micro/v3/util/codec" 24 ) 25 26 type Codec struct { 27 Conn io.ReadWriteCloser 28 } 29 30 // Frame gives us the ability to define raw data to send over the pipes 31 type Frame struct { 32 Data []byte 33 } 34 35 func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error { 36 return nil 37 } 38 39 func (c *Codec) ReadBody(b interface{}) error { 40 // read bytes 41 buf, err := ioutil.ReadAll(c.Conn) 42 if err != nil { 43 return err 44 } 45 46 switch v := b.(type) { 47 case *string: 48 *v = string(buf) 49 case *[]byte: 50 *v = buf 51 case *Frame: 52 v.Data = buf 53 default: 54 return fmt.Errorf("failed to read body: %v is not type of *[]byte", b) 55 } 56 57 return nil 58 } 59 60 func (c *Codec) Write(m *codec.Message, b interface{}) error { 61 var v []byte 62 switch ve := b.(type) { 63 case nil: 64 return nil 65 case *Frame: 66 v = ve.Data 67 case *[]byte: 68 v = *ve 69 case *string: 70 v = []byte(*ve) 71 case string: 72 v = []byte(ve) 73 case []byte: 74 v = ve 75 default: 76 return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b) 77 } 78 _, err := c.Conn.Write(v) 79 return err 80 } 81 82 func (c *Codec) Close() error { 83 return c.Conn.Close() 84 } 85 86 func (c *Codec) String() string { 87 return "text" 88 } 89 90 func NewCodec(c io.ReadWriteCloser) codec.Codec { 91 return &Codec{ 92 Conn: c, 93 } 94 }