3.9 KiB
3.9 KiB
| title | nav_order |
|---|---|
| Home | 1 |
Golang SDK for CloudEvents
Official CloudEvents SDK to integrate your application with CloudEvents.
This module will help you to:
- Represent CloudEvents in memory
- Use Event Formats to serialize/deserialize CloudEvents
- Use Protocol Bindings to send/receive CloudEvents
Note: Supported CloudEvents specification: 0.3, 1.0
Get started
Add the module as dependency using go mod:
% go get github.com/cloudevents/sdk-go/v2@V2.0.0-RC2
And import the module in your code
import cloudevents "github.com/cloudevents/sdk-go/v2"
Send your first CloudEvent
To send a CloudEvent using HTTP:
func main() {
// The default client is HTTP.
c, err := cloudevents.NewDefaultClient()
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
// Create an Event.
event := cloudevents.NewEvent()
event.SetSource("example/uri")
event.SetType("example.type")
event.SetData(cloudevents.ApplicationJSON, map[string]string{"hello": "world"})
// Set a target.
ctx := cloudevents.ContextWithTarget(context.Background(), "http://localhost:8080/")
// Send that Event.
if result := c.Send(ctx, event); !cloudevents.IsACK(result) {
log.Fatalf("failed to send, %v", result)
}
}
Receive your first CloudEvent
To start receiving CloudEvents using HTTP:
func receive(event cloudevents.Event) {
// do something with event.
fmt.Printf("%s", event)
}
func main() {
// The default client is HTTP.
c, err := cloudevents.NewDefaultClient()
if err != nil {
log.Fatalf("failed to create client, %v", err)
}
log.Fatal(c.StartReceiver(context.Background(), receive));
}
Serialize/Deserialize a CloudEvent
To marshal a CloudEvent into JSON:
event := cloudevents.NewEvent()
event.SetSource("example/uri")
event.SetType("example.type")
event.SetData(cloudevents.ApplicationJSON, map[string]string{"hello": "world"})
bytes, err := json.Marshal(event)
To unmarshal JSON back into a CloudEvent:
event := cloudevents.NewEvent()
err := json.Marshal(bytes, &event)
Supported specification features
| v0.3 | v1.0 | |
|---|---|---|
| CloudEvents Core | ✔️ | ✔️ |
| AMQP Protocol Binding | ✔️ | ✔️ |
| AVRO Event Format | ❌ | ❌ |
| HTTP Protocol Binding | ✔️ | ✔️ |
| JSON Event Format | ✔️ | ✔️ |
| Kafka Protocol Binding | ✔️ | ✔️ |
| MQTT Protocol Binding | ❌ | ❌ |
| NATS Protocol Binding | ✔️ | ✔️ |
| STAN Protocol Binding | ✔️ | ✔️ |
| Web hook | ❌ | ❌ |
Go further
*. Check out the examples *. Dig into the Godoc *. Learn about the architecture and concepts of the SDK *. How to use the CloudEvent in-memory representation *. How to use/implement a Protocol Binding