|
| 1 | +// Module included in the following assemblies |
| 2 | +// |
| 3 | +// * /serverless/functions/serverless-developing-go-functions.adoc |
| 4 | + |
| 5 | +[id="serverless-invoking-go-functions-cloudevent_{context}"] |
| 6 | += Functions triggered by a CloudEvent |
| 7 | + |
| 8 | +When an incoming CloudEvent is received, the event is invoked by the link:https://cloudevents.github.io/sdk-go/[CloudEvents Golang SDK] and the `Event` type as a parameter. |
| 9 | + |
| 10 | +You can leverage the Golang link:https://golang.org/pkg/context/[Context] as an optional parameter in the function contract, as shown in the list of supported function signatures: |
| 11 | + |
| 12 | +.Supported function signatures |
| 13 | +[source,go] |
| 14 | +---- |
| 15 | +Handle() |
| 16 | +Handle() error |
| 17 | +Handle(context.Context) |
| 18 | +Handle(context.Context) error |
| 19 | +Handle(cloudevents.Event) |
| 20 | +Handle(cloudevents.Event) error |
| 21 | +Handle(context.Context, cloudevents.Event) |
| 22 | +Handle(context.Context, cloudevents.Event) error |
| 23 | +Handle(cloudevents.Event) *cloudevents.Event |
| 24 | +Handle(cloudevents.Event) (*cloudevents.Event, error) |
| 25 | +Handle(context.Context, cloudevents.Event) *cloudevents.Event |
| 26 | +Handle(context.Context, cloudevents.Event) (*cloudevents.Event, error) |
| 27 | +---- |
| 28 | + |
| 29 | +[id="serverless-invoking-go-functions-cloudevent-example_{context}"] |
| 30 | +== CloudEvent trigger example |
| 31 | + |
| 32 | +A CloudEvent is received which contains a JSON string in the data property: |
| 33 | + |
| 34 | +[source,json] |
| 35 | +---- |
| 36 | +{ |
| 37 | + "customerId": "0123456", |
| 38 | + "productId": "6543210" |
| 39 | +} |
| 40 | +---- |
| 41 | + |
| 42 | +To access this data, a structure must be defined which maps properties in the CloudEvent data, and retrieves the data from the incoming event. The following example uses the `Purchase` structure: |
| 43 | + |
| 44 | +[source,go] |
| 45 | +---- |
| 46 | +type Purchase struct { |
| 47 | + CustomerId string `json:"customerId"` |
| 48 | + ProductId string `json:"productId"` |
| 49 | +} |
| 50 | +func Handle(ctx context.Context, event cloudevents.Event) (err error) { |
| 51 | +
|
| 52 | + purchase := &Purchase{} |
| 53 | + if err = event.DataAs(purchase); err != nil { |
| 54 | + fmt.Fprintf(os.Stderr, "failed to parse incoming CloudEvent %s\n", err) |
| 55 | + return |
| 56 | + } |
| 57 | + // ... |
| 58 | +} |
| 59 | +---- |
| 60 | + |
| 61 | +Alternatively, a Golang `encoding/json` package could be used to access the CloudEvent directly as JSON in the form of a bytes array: |
| 62 | + |
| 63 | +[source,go] |
| 64 | +---- |
| 65 | +func Handle(ctx context.Context, event cloudevents.Event) { |
| 66 | + bytes, err := json.Marshal(event) |
| 67 | + // ... |
| 68 | +} |
| 69 | +---- |
0 commit comments