github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/util/codec/bytes/bytes.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/bytes/bytes.go
    14  
    15  // Package bytes provides a bytes codec which does not encode or decode anything
    16  package bytes
    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 *[]byte:
    48  		*v = buf
    49  	case *Frame:
    50  		v.Data = buf
    51  	default:
    52  		return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
    53  	}
    54  
    55  	return nil
    56  }
    57  
    58  func (c *Codec) Write(m *codec.Message, b interface{}) error {
    59  	var v []byte
    60  	switch vb := b.(type) {
    61  	case nil:
    62  		return nil
    63  	case *Frame:
    64  		v = vb.Data
    65  	case *[]byte:
    66  		v = *vb
    67  	case []byte:
    68  		v = vb
    69  	default:
    70  		return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b)
    71  	}
    72  	_, err := c.Conn.Write(v)
    73  	return err
    74  }
    75  
    76  func (c *Codec) Close() error {
    77  	return c.Conn.Close()
    78  }
    79  
    80  func (c *Codec) String() string {
    81  	return "bytes"
    82  }
    83  
    84  func NewCodec(c io.ReadWriteCloser) codec.Codec {
    85  	return &Codec{
    86  		Conn: c,
    87  	}
    88  }