diff --git a/binding/format/protobuf/v2/protobuf.go b/binding/format/protobuf/v2/protobuf.go index 4b8c2544b..c85f9c18f 100644 --- a/binding/format/protobuf/v2/protobuf.go +++ b/binding/format/protobuf/v2/protobuf.go @@ -108,10 +108,12 @@ func ToProto(e *event.Event) (*pb.CloudEvent, error) { } container.Attributes[name] = attr } - container.Data = &pb.CloudEvent_BinaryData{ - BinaryData: e.Data(), + if e.Data() != nil { + container.Data = &pb.CloudEvent_BinaryData{ + BinaryData: e.Data(), + } } - if e.DataContentType() == ContentTypeProtobuf { + if e.Data() != nil && e.DataContentType() == ContentTypeProtobuf { anymsg := &anypb.Any{ TypeUrl: e.DataSchema(), Value: e.Data(), diff --git a/binding/format/protobuf/v2/protobuf_test.go b/binding/format/protobuf/v2/protobuf_test.go index 3099bc4ac..d89ccdf5b 100644 --- a/binding/format/protobuf/v2/protobuf_test.go +++ b/binding/format/protobuf/v2/protobuf_test.go @@ -6,6 +6,7 @@ package format_test import ( + "encoding/json" "net/url" "reflect" "testing" @@ -94,6 +95,36 @@ func TestProtobufFormatWithProtobufCodec(t *testing.T) { require.True(payload2.GetCeBoolean()) } +func TestProtobufFormatWithoutDataDoesNotCreateInvalidJSON(t *testing.T) { + require := require.New(t) + + e := event.New() + e.SetID("id") + e.SetSource("source") + e.SetType("type") + e.SetDataContentType(event.ApplicationJSON) + + b, err := format.Protobuf.Marshal(&e) + require.NoError(err) + + var e2 event.Event + require.NoError(format.Protobuf.Unmarshal(b, &e2)) + require.Nil(e2.DataEncoded) + + jsonData, err := e2.MarshalJSON() + require.NoError(err) + require.JSONEq(`{ + "specversion":"1.0", + "id":"id", + "source":"source", + "type":"type", + "datacontenttype":"application/json" + }`, string(jsonData)) + + var out event.Event + require.NoError(json.Unmarshal(jsonData, &out)) +} + func TestFromProto(t *testing.T) { tests := []struct { name string