Skip to content

Commit

Permalink
Handle +json Content-Type in accordance with RFC6839 (#416)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexdebrie authored and mthenw committed Apr 27, 2018
1 parent 5bf5be8 commit 744f4e0
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
8 changes: 6 additions & 2 deletions event/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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"))
}
20 changes: 20 additions & 0 deletions event/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down

0 comments on commit 744f4e0

Please sign in to comment.