2019-01-04 14:07:16 +00:00
|
|
|
// Package bytes provides a bytes codec which does not encode or decode anything
|
|
|
|
package bytes
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
|
2020-07-27 13:22:00 +01:00
|
|
|
"github.com/micro/go-micro/v3/codec"
|
2019-01-04 14:07:16 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type Codec struct {
|
|
|
|
Conn io.ReadWriteCloser
|
|
|
|
}
|
|
|
|
|
2019-01-16 15:27:57 +00:00
|
|
|
// Frame gives us the ability to define raw data to send over the pipes
|
|
|
|
type Frame struct {
|
|
|
|
Data []byte
|
|
|
|
}
|
|
|
|
|
2019-01-04 14:07:16 +00:00
|
|
|
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) ReadBody(b interface{}) error {
|
|
|
|
// read bytes
|
|
|
|
buf, err := ioutil.ReadAll(c.Conn)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-12-03 15:25:58 +08:00
|
|
|
switch v := b.(type) {
|
2019-01-16 15:27:57 +00:00
|
|
|
case *[]byte:
|
|
|
|
*v = buf
|
|
|
|
case *Frame:
|
|
|
|
v.Data = buf
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
|
|
|
|
}
|
|
|
|
|
2019-01-04 14:07:16 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Write(m *codec.Message, b interface{}) error {
|
2019-01-14 21:30:43 +00:00
|
|
|
var v []byte
|
2019-12-03 15:25:58 +08:00
|
|
|
switch vb := b.(type) {
|
2020-08-06 19:51:00 +02:00
|
|
|
case nil:
|
|
|
|
return nil
|
2019-01-16 15:27:57 +00:00
|
|
|
case *Frame:
|
2019-12-03 15:25:58 +08:00
|
|
|
v = vb.Data
|
2019-01-14 21:30:43 +00:00
|
|
|
case *[]byte:
|
2019-12-03 15:25:58 +08:00
|
|
|
v = *vb
|
2019-01-14 21:30:43 +00:00
|
|
|
case []byte:
|
2019-12-03 15:25:58 +08:00
|
|
|
v = vb
|
2019-01-14 21:30:43 +00:00
|
|
|
default:
|
|
|
|
return fmt.Errorf("failed to write: %v is not type of *[]byte or []byte", b)
|
2019-01-04 14:07:16 +00:00
|
|
|
}
|
2019-01-14 21:30:43 +00:00
|
|
|
_, err := c.Conn.Write(v)
|
2019-01-04 14:07:16 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) Close() error {
|
|
|
|
return c.Conn.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Codec) String() string {
|
|
|
|
return "bytes"
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCodec(c io.ReadWriteCloser) codec.Codec {
|
|
|
|
return &Codec{
|
|
|
|
Conn: c,
|
|
|
|
}
|
|
|
|
}
|