From 744f4e0a60eb2e6387d9a6a8385b5561b7d76646 Mon Sep 17 00:00:00 2001 From: Alex DeBrie Date: Fri, 27 Apr 2018 16:58:00 -0500 Subject: [PATCH] Handle +json Content-Type in accordance with RFC6839 (#416) --- event/event.go | 8 ++++++-- event/event_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/event/event.go b/event/event.go index 6cbe2bc..80c9eac 100644 --- a/event/event.go +++ b/event/event.go @@ -80,7 +80,7 @@ func New(eventType Type, mime string, payload interface{}) *Event { // which is why we change the event.Data type to "string" for forms, so that, it is left intact. if eventBody, ok := event.Data.([]byte); ok && len(eventBody) > 0 { switch { - case mime == mimeJSON: + case isJSONContent(mime): json.Unmarshal(eventBody, &event.Data) case strings.HasPrefix(mime, mimeFormMultipart), mime == mimeFormURLEncoded: event.Data = string(eventBody) @@ -122,7 +122,7 @@ func (e Event) IsSystem() bool { } func parseAsCloudEvent(eventType Type, mime string, payload interface{}) (*Event, error) { - if mime != mimeJSON { + if !isJSONContent(mime) { return nil, errors.New("content type is not json") } body, ok := payload.([]byte) @@ -149,3 +149,7 @@ func parseAsCloudEvent(eventType Type, mime string, payload interface{}) (*Event return nil, errors.New("couldn't cast to []byte") } + +func isJSONContent(mime string) bool { + return (mime == mimeJSON || strings.HasSuffix(mime, "+json")) +} diff --git a/event/event_test.go b/event/event_test.go index cb7c00f..01c8050 100644 --- a/event/event_test.go +++ b/event/event_test.go @@ -92,6 +92,26 @@ var newTests = []struct { Data: "test", }, }, + { + // valid CloudEvent with application/cloudevents+json Content-Type + eventpkg.Type("user.created"), + "application/cloudevents+json", + []byte(`{ + "eventType": "user.created", + "cloudEventsVersion": "`+ eventpkg.TransformationVersion +`", + "source": "/mysource", + "eventID": "6f6ada3b-0aa2-4b3c-989a-91ffc6405f11", + "contentType": "text/plain", + "data": "test" + }`), + eventpkg.Event{ + EventType: eventpkg.Type("user.created"), + CloudEventsVersion: eventpkg.TransformationVersion, + Source: "/mysource", + ContentType: "text/plain", + Data: "test", + }, + }, { // type mismatch eventpkg.Type("user.deleted"),