github.com/btccom/go-micro/v2@v2.9.3/codec/bytes/bytes.go (about)

     1  // Package bytes provides a bytes codec which does not encode or decode anything
     2  package bytes
     3  
     4  import (
     5  	"fmt"
     6  	"io"
     7  	"io/ioutil"
     8  
     9  	"github.com/btccom/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 *[]byte:
    34  		*v = buf
    35  	case *Frame:
    36  		v.Data = buf
    37  	default:
    38  		return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
    39  	}
    40  
    41  	return nil
    42  }
    43  
    44  func (c *Codec) Write(m *codec.Message, b interface{}) error {
    45  	var v []byte
    46  	switch vb := b.(type) {
    47  	case *Frame:
    48  		v = vb.Data
    49  	case *[]byte:
    50  		v = *vb
    51  	case []byte:
    52  		v = vb
    53  	default:
    54  		return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b)
    55  	}
    56  	_, err := c.Conn.Write(v)
    57  	return err
    58  }
    59  
    60  func (c *Codec) Close() error {
    61  	return c.Conn.Close()
    62  }
    63  
    64  func (c *Codec) String() string {
    65  	return "bytes"
    66  }
    67  
    68  func NewCodec(c io.ReadWriteCloser) codec.Codec {
    69  	return &Codec{
    70  		Conn: c,
    71  	}
    72  }