codec - Allow to Write() nil body (#1905)

* codec - Allow to Write() nil body

* Oops we are in v3 now
This commit is contained in:
Maarten Bezemer 2020-08-06 19:51:00 +02:00 committed by GitHub
parent fb8533b74e
commit 74907987d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 61 additions and 0 deletions

View File

@ -44,6 +44,8 @@ func (c *Codec) ReadBody(b interface{}) error {
func (c *Codec) Write(m *codec.Message, b interface{}) error { func (c *Codec) Write(m *codec.Message, b interface{}) error {
var v []byte var v []byte
switch vb := b.(type) { switch vb := b.(type) {
case nil:
return nil
case *Frame: case *Frame:
v = vb.Data v = vb.Data
case *[]byte: case *[]byte:

53
codec/codec_test.go Normal file
View File

@ -0,0 +1,53 @@
package codec_test
import (
"io"
"testing"
"github.com/micro/go-micro/v3/codec"
"github.com/micro/go-micro/v3/codec/bytes"
"github.com/micro/go-micro/v3/codec/grpc"
"github.com/micro/go-micro/v3/codec/json"
"github.com/micro/go-micro/v3/codec/jsonrpc"
"github.com/micro/go-micro/v3/codec/proto"
"github.com/micro/go-micro/v3/codec/protorpc"
"github.com/micro/go-micro/v3/codec/text"
)
type testRWC struct{}
func (rwc *testRWC) Read(p []byte) (n int, err error) {
return 0, nil
}
func (rwc *testRWC) Write(p []byte) (n int, err error) {
return 0, nil
}
func (rwc *testRWC) Close() error {
return nil
}
func getCodecs(c io.ReadWriteCloser) map[string]codec.Codec {
return map[string]codec.Codec{
"bytes": bytes.NewCodec(c),
"grpc": grpc.NewCodec(c),
"json": json.NewCodec(c),
"jsonrpc": jsonrpc.NewCodec(c),
"proto": proto.NewCodec(c),
"protorpc": protorpc.NewCodec(c),
"text": text.NewCodec(c),
}
}
func Test_WriteEmptyBody(t *testing.T) {
for name, c := range getCodecs(&testRWC{}) {
err := c.Write(&codec.Message{
Type: codec.Error,
Header: map[string]string{},
}, nil)
if err != nil {
t.Fatalf("codec %s - expected no error when writing empty/nil body: %s", name, err)
}
}
}

View File

@ -33,6 +33,10 @@ func (c *Codec) ReadBody(b interface{}) error {
} }
func (c *Codec) Write(m *codec.Message, b interface{}) error { func (c *Codec) Write(m *codec.Message, b interface{}) error {
if b == nil {
// Nothing to write
return nil
}
p, ok := b.(proto.Message) p, ok := b.(proto.Message)
if !ok { if !ok {
return codec.ErrInvalidMessage return codec.ErrInvalidMessage

View File

@ -46,6 +46,8 @@ func (c *Codec) ReadBody(b interface{}) error {
func (c *Codec) Write(m *codec.Message, b interface{}) error { func (c *Codec) Write(m *codec.Message, b interface{}) error {
var v []byte var v []byte
switch ve := b.(type) { switch ve := b.(type) {
case nil:
return nil
case *Frame: case *Frame:
v = ve.Data v = ve.Data
case *[]byte: case *[]byte: