Skip to content

Commit

Permalink
do not try to decode empty slice
Browse files Browse the repository at this point in the history
  • Loading branch information
rustatian committed Dec 14, 2020
1 parent e87f8d6 commit 42b3cbd
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
14 changes: 8 additions & 6 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,20 @@ func (c *ClientCodec) WriteRequest(r *rpc.Request, body interface{}) error {
// writeServiceMethod to the buffer
buf.WriteString(r.ServiceMethod)
// Initialize gob
enc := gob.NewEncoder(buf)
// write data to the gob
err := enc.Encode(body)
if err != nil {
return errors.E(op, err)
if body != nil {
enc := gob.NewEncoder(buf)
// write data to the gob
err := enc.Encode(body)
if err != nil {
return errors.E(op, err)
}
}

frame.WritePayloadLen(uint32(buf.Len()))
frame.WritePayload(buf.Bytes())
frame.WriteCRC()

err = c.relay.Send(frame)
err := c.relay.Send(frame)
if err != nil {
return errors.E(op, err)
}
Expand Down
21 changes: 18 additions & 3 deletions decoders.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,26 @@ func decodeJSON(out interface{}, frame *Frame) error {
if len(opts) != 2 {
return errors.E(op, errors.Str("should be 2 options. SEQ_ID and METHOD_LEN"))
}
return json.Unmarshal(frame.Payload()[opts[1]:], out)
payload := frame.Payload()[opts[1]:]
if len(payload) == 0 {
return nil
}
return json.Unmarshal(payload, out)
}

func decodeGob(out interface{}, frame *Frame) error {
const op = errors.Op("client: decode GOB")
buf := new(bytes.Buffer)
dec := gob.NewDecoder(buf)
opts := frame.ReadOptions()
if len(opts) != 2 {
return errors.E(op, errors.Str("should be 2 options. SEQ_ID and METHOD_LEN"))
}
payload := frame.Payload()[opts[1]:]
if len(payload) == 0 {
return nil
}

buf := new(bytes.Buffer)
dec := gob.NewDecoder(buf)
buf.Write(payload)

return dec.Decode(out)
Expand All @@ -38,6 +46,9 @@ func decodeRaw(out interface{}, frame *Frame) error {
return errors.E(op, errors.Str("should be 2 options. SEQ_ID and METHOD_LEN"))
}
payload := frame.Payload()[opts[1]:]
if len(payload) == 0 {
return nil
}

if raw, ok := out.(*[]byte); ok {
*raw = append(*raw, payload...)
Expand All @@ -54,5 +65,9 @@ func decodeMsgPack(out interface{}, frame *Frame) error {
return errors.E(op, errors.Str("should be 2 options. SEQ_ID and METHOD_LEN"))
}
payload := frame.Payload()[opts[1]:]
if len(payload) == 0 {
return nil
}

return msgpack.Unmarshal(payload, out)
}

0 comments on commit 42b3cbd

Please sign in to comment.