@@ -24,22 +24,13 @@ import (
2424 "strings"
2525 "time"
2626
27+ cloudevents "github.com/cloudevents/sdk-go/v2"
2728 "github.com/google/uuid"
2829 "github.com/kelseyhightower/envconfig"
2930)
3031
3132const contentType = "application/cloudevents+json"
3233
33- type ceBinaryStructure struct {
34- ID string `json:"id"`
35- Type string `json:"type"`
36- Source string `json:"source"`
37- Specversion string `json:"specversion"`
38- Time string `json:"time,omitempty"`
39- Contenttype string `json:"datacontenttype,omitempty"`
40- Data interface {} `json:"data,omitempty"`
41- }
42-
4334// CloudEvent is a data structure required to map KLR responses to cloudevents
4435type CloudEvent struct {
4536 // FunctionResponseMode describes what data is returned from the function:
@@ -94,38 +85,37 @@ func (ce *CloudEvent) Response(data []byte) ([]byte, error) {
9485 body = string (data )
9586 }
9687
97- b := ceBinaryStructure {
98- ID : uuid .NewString (),
99- Type : ce .Overrides .EventType ,
100- Time : time .Now ().Format (time .RFC3339 ),
101- Source : ce .Overrides .Source ,
102- Specversion : "1.0" ,
103- Contenttype : contentType ,
104- Data : body ,
105- }
106- return json .Marshal (b )
88+ event := cloudevents .NewEvent (cloudevents .VersionV1 )
89+ event .SetID (uuid .NewString ())
90+ event .SetType (ce .Overrides .EventType )
91+ event .SetTime (time .Now ())
92+ event .SetSource (ce .Overrides .Source )
93+ event .SetData (contentType , body )
94+ return event .MarshalJSON ()
10795}
10896
10997func (ce * CloudEvent ) fillInContext (data []byte ) ([]byte , error ) {
110- var response ceBinaryStructure
111- if err := json .Unmarshal (data , & response ); err != nil {
98+ var event map [ string ] interface {}
99+ if err := json .Unmarshal (data , & event ); err != nil {
112100 return nil , fmt .Errorf ("cannot unmarshal function response into binary CE: %w" , err )
113101 }
114102
115- if response . ID == "" {
116- response . ID = uuid .NewString ()
103+ if _ , set := event [ "id" ]; ! set {
104+ event [ "id" ] = uuid .NewString ()
117105 }
118- if response . Type == "" {
119- response . Type = ce .Overrides .EventType
106+ if _ , set := event [ "type" ]; ! set {
107+ event [ "type" ] = ce .Overrides .EventType
120108 }
121- if response . Source == "" {
122- response . Source = ce .Overrides .Source
109+ if _ , set := event [ "source" ]; ! set {
110+ event [ "source" ] = ce .Overrides .Source
123111 }
124- if response . Specversion == "" {
125- response . Specversion = "1.0"
112+ if _ , set := event [ "specversion" ]; ! set {
113+ event [ "specversion" ] = cloudevents . VersionV1
126114 }
127-
128- return json .Marshal (response )
115+ if _ , set := event ["time" ]; ! set {
116+ event ["time" ] = time .Now ().Format (time .RFC3339 )
117+ }
118+ return json .Marshal (event )
129119}
130120
131121func (ce * CloudEvent ) Request (request []byte , headers http.Header ) ([]byte , map [string ]string , error ) {
0 commit comments