Documentation
¶
Overview ¶
Package cloudevents is CloudEvents' two formats for the envelope family: binary mode, the default, and structured mode, each an envelope.Format.
Binary mode ¶
Binary puts the attributes in headers under a binding's prefix, ce- for HTTP and NATS, ce_ for Kafka, cloudEvents_ for AMQP 1.0, with the content type in envelope.Wire.ContentType and the payload as the body. Extensions are any other prefixed header, with the prefix stripped. That is the mapping the CloudEvents SDK uses, which is what makes this module's output readable by any other CloudEvents consumer. Values are percent-encoded, as both bindings require.
Binary is the one to prefer: attributes stay where anything routing on them can see them.
Structured mode ¶
Structured is the JSON event format: the whole event in the body as one object, with application/cloudevents+json as the content type. It is for a transport that limits its headers, such as SNS with its ten attributes.
Reading both ¶
envelope.Read with both formats takes either mode, and refuses a message both claim, so a reader can accept both while writers move from one to the other. Each format validates with envelope.Validate on the way out and on the way in, and returns what arrived but is not part of the event as envelope.Foreign.
The formats moved here from gitlab.com/phpboyscout/go/cloudevents, as go/messaging's spec 0014 D12 decided.
Index ¶
Examples ¶
Constants ¶
const ( // Prefix is what every attribute header key starts with, except // content-type. Prefix = "ce-" // HeaderContentType carries the datacontenttype attribute. HeaderContentType = "content-type" )
The wire mapping. Attributes ride in ce--prefixed headers; datacontenttype rides in the unprefixed content-type header the transport already has a meaning for.
const ( HeaderID = Prefix + "id" HeaderSource = Prefix + "source" HeaderSpecVersion = Prefix + "specversion" HeaderType = Prefix + "type" HeaderDataSchema = Prefix + "dataschema" HeaderSubject = Prefix + "subject" HeaderTime = Prefix + "time" // HeaderDataContentType is the NATS binding's spelling of datacontenttype. // // The two bindings genuinely differ here: the HTTP binding maps // datacontenttype onto Content-Type and says a ce-datacontenttype header // MUST NOT also be present, while the NATS binding prefixes it like every // other attribute. This codec writes the HTTP form — that is what the SDK's // NATS binding emits in practice — and accepts either on read, because // refusing a conformant NATS peer's content type would lose it silently. HeaderDataContentType = Prefix + "datacontenttype" )
The ce--prefixed header keys, in the canonical lower case this codec writes.
const StructuredContentType = "application/cloudevents+json"
StructuredContentType is the media type of a structured-mode message.
Variables ¶
var ( // HTTP is the HTTP binding's ce- prefix. RabbitMQ uses it too: no binding // covers AMQP 0-9-1, and its headers are closest to HTTP's. HTTP = Binding{/* contains filtered or unexported fields */} // NATS is the NATS binding's ce- prefix. NATS = Binding{/* contains filtered or unexported fields */} // Kafka is the Kafka binding's ce_ prefix. Kafka = Binding{/* contains filtered or unexported fields */} // AMQP is the AMQP 1.0 binding's cloudEvents_ prefix. The binding also // permits cloudEvents:, and says a consumer should understand both. AMQP = Binding{/* contains filtered or unexported fields */} )
var ( // ErrAmbiguousHeader is returned when one attribute arrives twice. // // Header maps differ in whether they fold case — http.Header canonicalises // keys, nats.Header does not — so this codec lower-cases on read. Two keys // that fold together with different values are then a real ambiguity, and // picking either would make the event mean different things on different // transports. ErrAmbiguousHeader = errors.NewSentinel("cloudevents.ambiguous_header", "cloudevents: an attribute was supplied more than once with different values") // ErrReadsAsStructured is returned when a binary-mode event's // datacontenttype starts application/cloudevents, the prefix every binding // reserves for structured mode. A strict reader would refuse the message // as [envelope.ErrAmbiguous], so the publisher is told instead of every consumer. ErrReadsAsStructured = errors.NewSentinel("cloudevents.reads_as_structured", "cloudevents: a binary-mode datacontenttype must not start application/cloudevents") // ErrInvalidJSON is returned when a structured-mode body is not a JSON // object of CloudEvents attributes. ErrInvalidJSON = errors.NewSentinel("cloudevents.invalid_json", "cloudevents: the structured-mode body is not a valid CloudEvents JSON object") )
The refusals only CloudEvents' own formats make. Everything else a format refuses is a go/envelope sentinel, so it is counted by the same code whichever format carried the event.
Functions ¶
func Binary ¶
Binary is CloudEvents binary mode for a binding: attributes in prefixed headers, the content type in envelope.Wire.ContentType, the payload as the body. It is marshal and unmarshal with the binding's prefix in place of ce-.
Header keys are matched without regard to case, as unmarshal matches ce-. Every header without one of the binding's prefixes, other than content-type, is envelope.Foreign; binary mode has no envelope a header can shadow, so it never reports a conflict.
Example ¶
ExampleBinary builds an event and renders it in binary mode for HTTP or NATS. SpecVersion is left unset because there is one value to write.
package main
import (
"fmt"
"maps"
"slices"
"time"
"gitlab.com/phpboyscout/go/envelope"
cloudevents "gitlab.com/phpboyscout/go/envelope-cloudevents"
)
func main() {
e := envelope.Event{
ID: "01JQ8Z3F7K2M4N6P8R0T2V4W6X",
Source: "/phpbotscout/ingest",
Type: "uk.phpboyscout.orders.created",
Subject: "order-4172",
Time: time.Date(2026, 8, 28, 11, 22, 33, 0, time.UTC),
DataContentType: "application/json",
Data: []byte(`{"order":"4172"}`),
}
w, err := cloudevents.Binary(cloudevents.HTTP).Encode(e)
if err != nil {
fmt.Println("encode:", err)
return
}
for _, key := range slices.Sorted(maps.Keys(w.Headers)) {
fmt.Printf("%s: %s\n", key, w.Headers[key][0])
}
fmt.Printf("content type %s\n\n%s\n", w.ContentType, w.Body)
}
Output: ce-id: 01JQ8Z3F7K2M4N6P8R0T2V4W6X ce-source: /phpbotscout/ingest ce-specversion: 1.0 ce-subject: order-4172 ce-time: 2026-08-28T11:22:33Z ce-type: uk.phpboyscout.orders.created content type application/json {"order":"4172"}
Example (Decode) ¶
ExampleBinary_decode reads an event whose headers are in the canonical case http.Header would have produced. Keys are folded on read, so both spellings work.
package main
import (
"fmt"
"gitlab.com/phpboyscout/go/envelope"
cloudevents "gitlab.com/phpboyscout/go/envelope-cloudevents"
)
func main() {
w := envelope.Wire{
ContentType: "application/json",
Headers: map[string][]string{
"Ce-Id": {"01JQ8Z3F7K2M4N6P8R0T2V4W6X"},
"Ce-Source": {"/phpbotscout/ingest"},
"Ce-Specversion": {"1.0"},
"Ce-Type": {"uk.phpboyscout.orders.created"},
"Ce-Scope": {"urn:phpboyscout:scope:continuity:01JQ8Z3F7K2M4N6P8R0T2V4W6X"},
},
Body: []byte(`{"order":"4172"}`),
}
e, _, err := cloudevents.Binary(cloudevents.HTTP).Decode(w)
if err != nil {
fmt.Println("decode:", err)
return
}
fmt.Println(e.Type)
fmt.Println(e.Extensions["scope"])
}
Output: uk.phpboyscout.orders.created urn:phpboyscout:scope:continuity:01JQ8Z3F7K2M4N6P8R0T2V4W6X
Example (Refused) ¶
ExampleBinary_refused shows the half that is easy to drop: a refused event still names itself, so a subscriber logs something traceable rather than "a message failed to parse".
package main
import (
"fmt"
"gitlab.com/phpboyscout/go/envelope"
"gitlab.com/phpboyscout/go/errors"
cloudevents "gitlab.com/phpboyscout/go/envelope-cloudevents"
)
func main() {
w := envelope.Wire{Headers: map[string][]string{
"ce-id": {"01JQ8Z3F7K2M4N6P8R0T2V4W6X"},
"ce-source": {"/phpbotscout/ingest"},
"ce-specversion": {"0.3"},
"ce-type": {"uk.phpboyscout.orders.created"},
}}
e, _, err := cloudevents.Binary(cloudevents.HTTP).Decode(w)
fmt.Println("refused:", errors.Is(err, envelope.ErrUnsupportedSpecVersion))
fmt.Println("but we still know which event:", e.ID)
}
Output: refused: true but we still know which event: 01JQ8Z3F7K2M4N6P8R0T2V4W6X
func Structured ¶
Structured is the CloudEvents JSON event format: the whole event in the body, as one JSON object, with StructuredContentType as the content type.
Every attribute is in the body, so a transport limited in how many headers it carries is limited no longer, and a payload that is not UTF-8 travels as data_base64. The cost is the reason binary mode stays the default: anything routing on an attribute has to read the body to see it.
A payload whose datacontenttype is JSON, or absent, travels verbatim as the data member when it is valid JSON with no surrounding whitespace, so it reads back byte for byte; anything else travels as data_base64. On read, extension members that are JSON numbers or booleans become their JSON text, because envelope.Event.Extensions holds strings. Every header on the wire but content-type is envelope.Foreign: in structured mode the event is the body.
Example ¶
ExampleStructured renders an event in structured mode: every attribute in the body, so a transport that limits its headers carries it whole.
package main
import (
"fmt"
"gitlab.com/phpboyscout/go/envelope"
cloudevents "gitlab.com/phpboyscout/go/envelope-cloudevents"
)
func main() {
e := envelope.Event{
ID: "01JQ8Z3F7K2M4N6P8R0T2V4W6X",
Source: "/phpbotscout/ingest",
Type: "uk.phpboyscout.orders.created",
DataContentType: "application/json",
Data: []byte(`{"order":"4172"}`),
}
w, err := cloudevents.Structured().Encode(e)
if err != nil {
fmt.Println("encode:", err)
return
}
fmt.Println(w.ContentType)
fmt.Printf("%s\n", w.Body)
}
Output: application/cloudevents+json {"datacontenttype":"application/json","id":"01JQ8Z3F7K2M4N6P8R0T2V4W6X","source":"/phpbotscout/ingest","specversion":"1.0","type":"uk.phpboyscout.orders.created","data":{"order":"4172"}}