Golang SDK for CloudEvents

Official CloudEvents SDK to integrate your application with CloudEvents.

This module will help you to:

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.6.0

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() {
	c, err := cloudevents.NewClientHTTP()
	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.NewClientHTTP()
	if err != nil {
		log.Fatalf("failed to create client, %v", err)
	}
	log.Fatal(c.StartReceiver(context.Background(), receive));
}

Create a CloudEvent from an HTTP Request

func handler(w http.ResponseWriter, r *http.Request) {
	event, err := cloudevents.NewEventFromHTTPRequest(r)
	if err != nil {
		log.Print("failed to parse CloudEvent from request: %v", err)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
	}
	w.Write([]byte(*event.String()))
}

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.Unmarshal(bytes, &event)

Supported specification features

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