cloudevents

package module
v2.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 16, 2020 License: Apache-2.0 Imports: 8 Imported by: 0

README

Go SDK for CloudEvents

go-doc Go Report Card CircleCI Releases LICENSE

Status

This SDK is still considered work in progress.

For v1 of the SDK, see CloudEvents Go SDK v1.

v2.0.0-preview2:

In preview2 we are focusing on the new Client interface:

type Client interface {
	Send(ctx context.Context, event event.Event) error
	Request(ctx context.Context, event event.Event) (*event.Event, error)
	StartReceiver(ctx context.Context, fn interface{}) error
}

Where a full fn looks like func(context.Context, event.Event) (*event.Event, transport.Result)

For protocols that do not support responses, StartReceiver will throw an error when attempting to set a receiver fn with that capability.

For protocols that do not support responses from send (Requester interface), Client.Request will throw an error.

v2.0.0-preview1:

In preview1 we are focusing on the new interfaces found in pkg/transport (will be renamed to protocol):

  • Sender, Send an event.
  • Requester, Send an event and expect a response.
  • Receiver, Receive an event.
  • Responder, Receive an event and respond.

Working with CloudEvents

Note: Supported CloudEvents specification: [0.3, 1.0].

Import this repo to get the cloudevents package:

import cloudevents "github.com/cloudevents/sdk-go"

To marshal a CloudEvent into JSON, use event.Event directly:

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)

The aim of CloudEvents Specification is to define how to "bind" an event to a particular protocol and back. This SDK wraps the protocol binding implementations in a client to expose a simple event.Event based API.

An example of sending a cloudevents.Event via 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 err := c.Send(ctx, event); err != nil {
		log.Fatalf("failed to send, %v", err)}
	}
}

An example of receiving a cloudevents.Event via 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));
}

Checkout the sample sender and receiver applications for working demo.

It can be more performant to not parse an event all the way to the event.Event. For this the package binding provides primitives convert event.Event to binding.Message, and then bind an them onto a protocol implementation.

For example, to convert an event.Event to a binding.Message and then create an http.Request:

msg := cloudevents.ToMessage(&event)

req, _ = nethttp.NewRequest("POST", "http://localhost", nil)
err = http.WriteRequest(context.TODO(), msg, req, nil)
// ...check error.

// Then use req:
resp, err := http.DefaultClient.Do(req)

Community

  • There are bi-weekly calls immediately following the Serverless/CloudEvents call at 9am PT (US Pacific). Which means they will typically start at 10am PT, but if the other call ends early then the SDK call will start early as well. See the CloudEvents meeting minutes to determine which week will have the call.
  • Slack: #cloudeventssdk channel under CNCF's Slack workspace.
  • Contact for additional information: Scott Nichols (@Scott Nichols on slack).

Documentation

Index

Constants

View Source
const (
	ApplicationXML                  = event.ApplicationXML
	ApplicationJSON                 = event.ApplicationJSON
	TextPlain                       = event.TextPlain
	ApplicationCloudEventsJSON      = event.ApplicationCloudEventsJSON
	ApplicationCloudEventsBatchJSON = event.ApplicationCloudEventsBatchJSON
	Base64                          = event.Base64

	VersionV1  = event.CloudEventsVersionV1
	VersionV03 = event.CloudEventsVersionV03

	EncodingBinary     = binding.EncodingBinary
	EncodingStructured = binding.EncodingStructured
)

Variables

View Source
var (
	StringOfApplicationJSON                 = event.StringOfApplicationJSON
	StringOfApplicationXML                  = event.StringOfApplicationXML
	StringOfTextPlain                       = event.StringOfTextPlain
	StringOfApplicationCloudEventsJSON      = event.StringOfApplicationCloudEventsJSON
	StringOfApplicationCloudEventsBatchJSON = event.StringOfApplicationCloudEventsBatchJSON
	StringOfBase64                          = event.StringOfBase64

	NewClient             = client.New
	NewClientObserved     = client.NewObserved
	NewDefaultClient      = client.NewDefault
	NewHTTPReceiveHandler = client.NewHTTPReceiveHandler

	WithEventDefaulter   = client.WithEventDefaulter
	WithUUIDs            = client.WithUUIDs
	WithTimeNow          = client.WithTimeNow
	WithTracePropagation = client.WithTracePropagation()

	NewEvent  = event.New
	NewResult = protocol.NewResult

	NewHTTPResult = http.NewResult

	ToMessage = binding.ToMessage

	WriteHTTPRequest = http.WriteRequest

	EnableTracing = observability.EnableTracing

	ContextWithTarget      = context.WithTarget
	TargetFromContext      = context.TargetFrom
	WithEncodingBinary     = binding.WithForceBinary
	WithEncodingStructured = binding.WithForceStructured

	ParseTimestamp = types.ParseTimestamp
	ParseURIRef    = types.ParseURIRef
	ParseURI       = types.ParseURI

	NewHTTP = http.New

	WithTarget          = http.WithTarget
	WithHeader          = http.WithHeader
	WithShutdownTimeout = http.WithShutdownTimeout
	//WithEncoding           = http.WithEncoding
	//WithStructuredEncoding = http.WithStructuredEncoding // TODO: expose new way
	WithPort          = http.WithPort
	WithPath          = http.WithPath
	WithMiddleware    = http.WithMiddleware
	WithListener      = http.WithListener
	WithHTTPTransport = http.WithHTTPTransport
)

Functions

This section is empty.

Types

type Client

type Client = client.Client

type ClientOption

type ClientOption client.Option

type Encoding

type Encoding = binding.Encoding

type Event

type Event = event.Event

type EventContext

type EventContext = event.EventContext

type EventContextV03

type EventContextV03 = event.EventContextV03

type EventContextV1

type EventContextV1 = event.EventContextV1

type HTTPOption

type HTTPOption http.Option

type HTTPProtocol

type HTTPProtocol = http.Protocol

type Message

type Message = binding.Message

type Timestamp

type Timestamp = types.Timestamp

type URIRef

type URIRef = types.URIRef

Directories

Path Synopsis
cmd
pkg
binding/test
Package test contains test data and generic tests for testing bindings.
Package test contains test data and generic tests for testing bindings.
client
Package client holds the recommended entry points for interacting with the CloudEvents Golang SDK.
Package client holds the recommended entry points for interacting with the CloudEvents Golang SDK.
context
Package context holds the last resort overrides and fyi objects that can be passed to clients and transports added to context.Context objects.
Package context holds the last resort overrides and fyi objects that can be passed to clients and transports added to context.Context objects.
event
Package cloudevents provides primitives to work with CloudEvents specification: https://github.com/cloudevents/spec.
Package cloudevents provides primitives to work with CloudEvents specification: https://github.com/cloudevents/spec.
event/datacodec
Package datacodec holds the data codec registry and adds known encoders and decoders supporting media types such as `application/json` and `application/xml`.
Package datacodec holds the data codec registry and adds known encoders and decoders supporting media types such as `application/json` and `application/xml`.
event/datacodec/json
Package json holds the encoder/decoder implementation for `application/json`.
Package json holds the encoder/decoder implementation for `application/json`.
event/datacodec/text
Text codec converts []byte or string to string and vice-versa.
Text codec converts []byte or string to string and vice-versa.
event/datacodec/xml
Package xml holds the encoder/decoder implementation for `application/xml`.
Package xml holds the encoder/decoder implementation for `application/xml`.
observability
Package observability holds metrics and tracing recording implementations.
Package observability holds metrics and tracing recording implementations.
protocol/amqp
Module amqp implements an AMQP binding using pack.ag/amqp module
Module amqp implements an AMQP binding using pack.ag/amqp module
protocol/nats
Package nats implements the CloudEvent transport implementation using NATS.
Package nats implements the CloudEvent transport implementation using NATS.
protocol/test
Package test provides re-usable functions for binding tests.
Package test provides re-usable functions for binding tests.
types
Package types implements the CloudEvents type system.
Package types implements the CloudEvents type system.
test

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL