Allow bytes.Frame to be set to sent just bytes

This commit is contained in:
Asim Aslam 2019-01-16 15:27:57 +00:00
parent a9c0b95603
commit 784a89b488
3 changed files with 32 additions and 13 deletions

View File

@ -106,12 +106,12 @@ func (c *rpcCodec) Write(m *codec.Message, body interface{}) error {
m.Header["X-Micro-Service"] = m.Target
m.Header["X-Micro-Endpoint"] = m.Endpoint
// if body is bytes don't encode
// if body is bytes Frame don't encode
if body != nil {
b, ok := body.([]byte)
b, ok := body.(*raw.Frame)
if ok {
// set body
m.Body = b
m.Body = b.Data
body = nil
}
}

View File

@ -13,30 +13,41 @@ type Codec struct {
Conn io.ReadWriteCloser
}
// Frame gives us the ability to define raw data to send over the pipes
type Frame struct {
Data []byte
}
func (c *Codec) ReadHeader(m *codec.Message, t codec.MessageType) error {
return nil
}
func (c *Codec) ReadBody(b interface{}) error {
v, ok := b.(*[]byte)
if !ok {
return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
}
// read bytes
buf, err := ioutil.ReadAll(c.Conn)
if err != nil {
return err
}
// set bytes
*v = buf
switch b.(type) {
case *[]byte:
v := b.(*[]byte)
*v = buf
case *Frame:
v := b.(*Frame)
v.Data = buf
default:
return fmt.Errorf("failed to read body: %v is not type of *[]byte", b)
}
return nil
}
func (c *Codec) Write(m *codec.Message, b interface{}) error {
var v []byte
switch b.(type) {
case *Frame:
v = b.(*Frame).Data
case *[]byte:
ve := b.(*[]byte)
v = *ve

View File

@ -127,6 +127,12 @@ func (c *rpcCodec) ReadBody(b interface{}) error {
if len(c.req.Body) == 0 {
return nil
}
// read raw data
if v, ok := b.(*raw.Frame); ok {
v.Data = c.req.Body
return nil
}
// decode the usual way
return c.codec.ReadBody(b)
}
@ -168,8 +174,11 @@ func (c *rpcCodec) Write(r *codec.Message, b interface{}) error {
// the body being sent
var body []byte
// if we have encoded data just send it
if len(r.Body) > 0 {
// is it a raw frame?
if v, ok := b.(*raw.Frame); ok {
body = v.Data
// if we have encoded data just send it
} else if len(r.Body) > 0 {
body = r.Body
// write the body to codec
} else if err := c.codec.Write(m, b); err != nil {
@ -182,7 +191,6 @@ func (c *rpcCodec) Write(r *codec.Message, b interface{}) error {
if err := c.codec.Write(m, nil); err != nil {
return err
}
// write the body
} else {
// set the body
body = c.buf.wbuf.Bytes()