Added binary data type detection (#631)

* Added binary data type detection
Added base64 encoding for binary data types

* Update utils.go

Co-authored-by: Artur Souza <artursouza.ms@outlook.com>
This commit is contained in:
Jigar 2021-01-26 12:38:47 +05:30 committed by GitHub
parent 97912e75c6
commit 27344d4e4c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 20 additions and 1 deletions

View File

@ -24,6 +24,15 @@ func IsJSONContentType(contentType string) bool {
return isContentType(contentType, JSONContentType)
}
// IsStringContentType determines if content type is string
func IsStringContentType(contentType string) bool {
if strings.HasPrefix(strings.ToLower(contentType), "text/") {
return true
}
return isContentType(contentType, "application/xml")
}
func isContentType(contentType string, expected string) bool {
lowerContentType := strings.ToLower(contentType)
if lowerContentType == expected {

View File

@ -6,6 +6,7 @@
package pubsub
import (
"encoding/base64"
"fmt"
"time"
@ -57,8 +58,10 @@ func NewCloudEventsEnvelope(id, source, eventType, subject string, topic string,
var err error
if contrib_contenttype.IsJSONContentType(dataContentType) {
err = jsoniter.Unmarshal(data, &ceData)
} else {
} else if contrib_contenttype.IsStringContentType(dataContentType) {
ceData = string(data)
} else {
ceData = base64.StdEncoding.EncodeToString(data)
}
if err != nil {

View File

@ -6,6 +6,7 @@
package pubsub
import (
"encoding/base64"
"encoding/json"
"fmt"
"math"
@ -198,3 +199,9 @@ func TestNewFromExisting(t *testing.T) {
assert.Error(t, err)
})
}
func TestCreateFromBinaryPayload(t *testing.T) {
base64Encoding := base64.StdEncoding.EncodeToString([]byte{0x1})
envelope := NewCloudEventsEnvelope("", "", "", "", "", "", "application/octet-stream", []byte{0x1}, "trace")
assert.Equal(t, base64Encoding, envelope[DataField])
}