code
stringlengths
22
960k
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
245
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
func (v *version) HasPrefix(name string) bool { return strings.HasPrefix(strings.ToLower(name), v.prefix) }
HasPrefix is a case-insensitive prefix check.
HasPrefix
go
cloudevents/sdk-go
v2/binding/spec/spec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/spec/spec.go
Apache-2.0
func WithPrefix(prefix string) *Versions { attr := func(name string, kind Kind) *attribute { return &attribute{accessor: acc[kind], name: name} } vs := &Versions{ m: map[string]Version{}, prefix: prefix, all: []Version{ newVersion(prefix, event.EventContextV1{}.AsV1(), func(c event.EventContextCo...
WithPrefix returns a set of versions with prefix added to all attribute names.
WithPrefix
go
cloudevents/sdk-go
v2/binding/spec/spec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/spec/spec.go
Apache-2.0
func MustCreateMockBinaryMessage(e event.Event) binding.Message { version := spec.VS.Version(e.SpecVersion()) m := MockBinaryMessage{ Version: version, Metadata: make(map[spec.Attribute]interface{}), Extensions: make(map[string]interface{}), } for _, attribute := range version.Attributes() { val := a...
MustCreateMockBinaryMessage creates a new MockBinaryMessage starting from an event.Event. Panics in case of error
MustCreateMockBinaryMessage
go
cloudevents/sdk-go
v2/binding/test/mock_binary_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/test/mock_binary_message.go
Apache-2.0
func MustCreateMockStructuredMessage(t testing.TB, e event.Event) binding.Message { return &MockStructuredMessage{ Bytes: test.MustJSON(t, e), Format: format.JSON, } }
MustCreateMockStructuredMessage creates a new MockStructuredMessage starting from an event.Event. Panics in case of error.
MustCreateMockStructuredMessage
go
cloudevents/sdk-go
v2/binding/test/mock_structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/test/mock_structured_message.go
Apache-2.0
func AddAttribute(attributeKind spec.Kind, value interface{}) binding.TransformerFunc { return SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) { if types.IsZero(i2) { return value, nil } return i2, nil }) }
AddAttribute adds a cloudevents attribute (if missing) during the encoding process
AddAttribute
go
cloudevents/sdk-go
v2/binding/transformer/add_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/add_metadata.go
Apache-2.0
func AddExtension(name string, value interface{}) binding.TransformerFunc { return SetExtension(name, func(i2 interface{}) (i interface{}, err error) { if types.IsZero(i2) { return value, nil } return i2, nil }) }
AddExtension adds a cloudevents extension (if missing) during the encoding process
AddExtension
go
cloudevents/sdk-go
v2/binding/transformer/add_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/add_metadata.go
Apache-2.0
func DeleteAttribute(attributeKind spec.Kind) binding.TransformerFunc { return SetAttribute(attributeKind, func(i2 interface{}) (i interface{}, err error) { return nil, nil }) }
DeleteAttribute deletes a cloudevents attribute during the encoding process
DeleteAttribute
go
cloudevents/sdk-go
v2/binding/transformer/delete_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/delete_metadata.go
Apache-2.0
func DeleteExtension(name string) binding.TransformerFunc { return SetExtension(name, func(i2 interface{}) (i interface{}, err error) { return nil, nil }) }
DeleteExtension deletes a cloudevents extension during the encoding process
DeleteExtension
go
cloudevents/sdk-go
v2/binding/transformer/delete_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/delete_metadata.go
Apache-2.0
func SetAttribute(attribute spec.Kind, updater func(interface{}) (interface{}, error)) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { attr, oldVal := reader.GetAttribute(attribute) if attr == nil { // The spec version of this message doe...
SetAttribute sets a cloudevents attribute using the provided function. updater gets a zero value as input if no previous value was found. To test a zero value, use types.IsZero(). updater must return nil, nil if the user wants to remove the attribute
SetAttribute
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata.go
Apache-2.0
func SetExtension(name string, updater func(interface{}) (interface{}, error)) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { oldVal := reader.GetExtension(name) newVal, err := updater(oldVal) if err != nil { return err } return wr...
SetExtension sets a cloudevents extension using the provided function. updater gets a zero value as input if no previous value was found. To test a zero value, use types.IsZero() updater must return nil, nil if the user wants to remove the extension
SetExtension
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata.go
Apache-2.0
func TestSetExtension(t *testing.T) { e := MinEvent() e.Context = e.Context.AsV1() extName := "exnum" extInitialValue := "1" exUpdatedValue := "2" eventWithInitialValue := e.Clone() require.NoError(t, eventWithInitialValue.Context.SetExtension(extName, extInitialValue)) eventWithUpdatedValue := e.Clone() re...
Test a common flow: If the metadata is not existing, initialize with a value. Otherwise, update it
TestSetExtension
go
cloudevents/sdk-go
v2/binding/transformer/set_metadata_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/set_metadata_test.go
Apache-2.0
func Version(newVersion spec.Version) binding.TransformerFunc { return func(reader binding.MessageMetadataReader, writer binding.MessageMetadataWriter) error { _, sv := reader.GetAttribute(spec.SpecVersion) if newVersion.String() == sv { return nil } for _, newAttr := range newVersion.Attributes() { old...
Version converts the event context version to the specified one.
Version
go
cloudevents/sdk-go
v2/binding/transformer/version.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/transformer/version.go
Apache-2.0
func NewStructuredMessage(format format.Format, reader io.Reader) *genericStructuredMessage { return &genericStructuredMessage{reader: reader, format: format} }
NewStructuredMessage wraps a format and an io.Reader returning an implementation of Message This message *cannot* be read several times safely
NewStructuredMessage
go
cloudevents/sdk-go
v2/binding/utils/structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/utils/structured_message.go
Apache-2.0
func WriteStructured(ctx context.Context, m binding.Message, writer io.Writer, transformers ...binding.Transformer) error { _, err := binding.Write( ctx, m, wsMessageWriter{writer}, nil, transformers..., ) return err }
WriteStructured fills the provided io.Writer with the binding.Message m in structured mode. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteStructured
go
cloudevents/sdk-go
v2/binding/utils/write_structured_message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/binding/utils/write_structured_message.go
Apache-2.0
func New(obj interface{}, opts ...Option) (Client, error) { c := &ceClient{ // Running runtime.GOMAXPROCS(0) doesn't update the value, just returns the current one pollGoroutines: runtime.GOMAXPROCS(0), observabilityService: noopObservabilityService{}, } if p, ok := obj.(protocol.Sender); ok { c.sende...
New produces a new client with the provided transport object and applied client options.
New
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func (c *ceClient) StartReceiver(ctx context.Context, fn interface{}) error { ctx, cancel := context.WithCancel(ctx) defer cancel() c.receiverMu.Lock() defer c.receiverMu.Unlock() if c.invoker != nil { return fmt.Errorf("client already has a receiver") } invoker, err := newReceiveInvoker( fn, c.observab...
StartReceiver sets up the given fn to handle Receive. See Client.StartReceiver for details. This is a blocking call.
StartReceiver
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func noRespFn(_ context.Context, _ binding.Message, r protocol.Result, _ ...binding.Transformer) error { return r }
noRespFn is used to simply forward the protocol.Result for receivers that aren't responders
noRespFn
go
cloudevents/sdk-go
v2/client/client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client.go
Apache-2.0
func NewHTTP(opts ...http.Option) (Client, error) { p, err := http.New(opts...) if err != nil { return nil, err } c, err := New(p, WithTimeNow(), WithUUIDs()) if err != nil { return nil, err } return c, nil }
NewHTTP provides the good defaults for the common case using an HTTP Protocol client. The WithTimeNow, and WithUUIDs client options are also applied to the client, all outbound events will have a time and id set if not already present.
NewHTTP
go
cloudevents/sdk-go
v2/client/client_http.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/client_http.go
Apache-2.0
func DefaultIDToUUIDIfNotSet(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.ID() == "" { event.Context = event.Context.Clone() event.SetID(uuid.New().String()) } } return event }
DefaultIDToUUIDIfNotSet will inspect the provided event and assign a UUID to context.ID if it is found to be empty.
DefaultIDToUUIDIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func DefaultTimeToNowIfNotSet(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.Time().IsZero() { event.Context = event.Context.Clone() event.SetTime(time.Now()) } } return event }
DefaultTimeToNowIfNotSet will inspect the provided event and assign a new Timestamp to context.Time if it is found to be nil or zero.
DefaultTimeToNowIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func NewDefaultDataContentTypeIfNotSet(contentType string) EventDefaulter { return func(ctx context.Context, event event.Event) event.Event { if event.Context != nil { if event.DataContentType() == "" { event.SetDataContentType(contentType) } } return event } }
NewDefaultDataContentTypeIfNotSet returns a defaulter that will inspect the provided event and set the provided content type if content type is found to be empty.
NewDefaultDataContentTypeIfNotSet
go
cloudevents/sdk-go
v2/client/defaulters.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/defaulters.go
Apache-2.0
func WithEventDefaulter(fn EventDefaulter) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { if fn == nil { return fmt.Errorf("client option was given an nil event defaulter") } c.eventDefaulterFns = append(c.eventDefaulterFns, fn) } return nil } }
WithEventDefaulter adds an event defaulter to the end of the defaulter chain.
WithEventDefaulter
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithUUIDs() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultIDToUUIDIfNotSet) } return nil } }
WithUUIDs adds DefaultIDToUUIDIfNotSet event defaulter to the end of the defaulter chain.
WithUUIDs
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithTimeNow() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.eventDefaulterFns = append(c.eventDefaulterFns, DefaultTimeToNowIfNotSet) } return nil } }
WithTimeNow adds DefaultTimeToNowIfNotSet event defaulter to the end of the defaulter chain.
WithTimeNow
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithTracePropagation() Option { return func(i interface{}) error { return nil } }
WithTracePropagation enables trace propagation via the distributed tracing extension. Deprecated: this is now noop and will be removed in future releases. Don't use distributed tracing extension to propagate traces: https://github.com/cloudevents/spec/blob/v1.0.1/extensions/distributed-tracing.md#using-the-distributed-...
WithTracePropagation
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithPollGoroutines(pollGoroutines int) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.pollGoroutines = pollGoroutines } return nil } }
WithPollGoroutines configures how much goroutines should be used to poll the Receiver/Responder/Protocol implementations. Default value is GOMAXPROCS
WithPollGoroutines
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithObservabilityService(service ObservabilityService) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.observabilityService = service c.inboundContextDecorators = append(c.inboundContextDecorators, service.InboundContextDecorators()...) } return nil } }
WithObservabilityService configures the observability service to use to record traces and metrics
WithObservabilityService
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithInboundContextDecorator(dec func(context.Context, binding.Message) context.Context) Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.inboundContextDecorators = append(c.inboundContextDecorators, dec) } return nil } }
WithInboundContextDecorator configures a new inbound context decorator. Inbound context decorators are invoked to wrap additional informations from the binding.Message and propagate these informations in the context passed to the event receiver.
WithInboundContextDecorator
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithBlockingCallback() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.blockingCallback = true } return nil } }
WithBlockingCallback makes the callback passed into StartReceiver is executed as a blocking call, i.e. in each poll go routine, the next event will not be received until the callback on current event completes. To make event processing serialized (no concurrency), use this option along with WithPollGoroutines(1)
WithBlockingCallback
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func WithAckMalformedEvent() Option { return func(i interface{}) error { if c, ok := i.(*ceClient); ok { c.ackMalformedEvent = true } return nil } }
WithAckMalformedevents causes malformed events received within StartReceiver to be acknowledged rather than being permanently not-acknowledged. This can be useful when a protocol does not provide a responder implementation and would otherwise cause the receiver to be partially or fully stuck.
WithAckMalformedEvent
go
cloudevents/sdk-go
v2/client/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/options.go
Apache-2.0
func receiver(fn interface{}) (*receiverFn, error) { fnType := reflect.TypeOf(fn) if fnType.Kind() != reflect.Func { return nil, errors.New("must pass a function to handle events") } r := &receiverFn{ fnValue: reflect.ValueOf(fn), numIn: fnType.NumIn(), numOut: fnType.NumOut(), } if err := r.validate...
receiver creates a receiverFn wrapper class that is used by the client to validate and invoke the provided function. Valid fn signatures are: * func() * func() protocol.Result * func(context.Context) * func(context.Context) protocol.Result * func(event.Event) * func(event.Event) transport.Result * func(context.Context,...
receiver
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validateInParamSignature(fnType reflect.Type) error { r.hasContextIn = false r.hasEventIn = false switch fnType.NumIn() { case 2: // has to be (context.Context, event.Event) if !eventType.ConvertibleTo(fnType.In(1)) { return fmt.Errorf("%s; cannot convert parameter 2 to %s from event.Ev...
Verifies that the inputs to a function have a valid signature Valid input is to be [0, all] of context.Context, event.Event in this order.
validateInParamSignature
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validateOutParamSignature(fnType reflect.Type) error { r.hasEventOut = false r.hasResultOut = false switch fnType.NumOut() { case 2: // has to be (*event.Event, transport.Result) if !fnType.Out(1).ConvertibleTo(resultType) { return fmt.Errorf("%s; cannot convert parameter 2 from %s to e...
Verifies that the outputs of a function have a valid signature Valid output signatures to be [0, all] of *event.Event, transport.Result in this order
validateOutParamSignature
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func (r *receiverFn) validate(fnType reflect.Type) error { if err := r.validateInParamSignature(fnType); err != nil { return err } if err := r.validateOutParamSignature(fnType); err != nil { return err } return nil }
validateReceiverFn validates that a function has the right number of in and out params and that they are of allowed types.
validate
go
cloudevents/sdk-go
v2/client/receiver.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/receiver.go
Apache-2.0
func NewMockSenderClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, <-chan event.Event) { require.NotZero(t, chanSize) eventCh := make(chan event.Event, chanSize) messageCh := make(chan binding.Message) // Output piping go func(messageCh <-chan binding.Message, eventCh chan<- event.Event)...
NewMockSenderClient returns a client that can Send() event. All sent messages are delivered to the returned channel.
NewMockSenderClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockRequesterClient(t *testing.T, chanSize int, replierFn func(inMessage event.Event) (*event.Event, protocol.Result), opts ...client.Option) (client.Client, <-chan event.Event) { require.NotZero(t, chanSize) require.NotNil(t, replierFn) eventCh := make(chan event.Event, chanSize) messageCh := make(chan bi...
NewMockRequesterClient returns a client that can perform Send() event and Request() event. All sent messages are delivered to the returned channel.
NewMockRequesterClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockReceiverClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, chan<- event.Event) { require.NotZero(t, chanSize) eventCh := make(chan event.Event, chanSize) messageCh := make(chan binding.Message) // Input piping go func(messageCh chan<- binding.Message, eventCh <-chan event.Event...
NewMockReceiverClient returns a client that can Receive events, without replying. The returned channel is the channel for sending messages to the client
NewMockReceiverClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func NewMockResponderClient(t *testing.T, chanSize int, opts ...client.Option) (client.Client, chan<- event.Event, <-chan ClientMockResponse) { require.NotZero(t, chanSize) inEventCh := make(chan event.Event, chanSize) inMessageCh := make(chan binding.Message) outEventCh := make(chan ClientMockResponse, chanSize)...
NewMockResponderClient returns a client that can Receive events and reply. The first returned channel is the channel for sending messages to the client, while the second one contains the eventual responses.
NewMockResponderClient
go
cloudevents/sdk-go
v2/client/test/mock_client.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/mock_client.go
Apache-2.0
func SendReceive(t *testing.T, protocolFactory func() interface{}, in event.Event, outAssert func(e event.Event), opts ...client.Option) { t.Helper() pf := protocolFactory() // Create a sender and receiver client since we can't assume it's safe // to use the same one for both roles sender, err := client.New(pf, ...
SendReceive does client.Send(in), then it receives the message using client.StartReceiver() and executes outAssert Halt test on error.
SendReceive
go
cloudevents/sdk-go
v2/client/test/test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/client/test/test.go
Apache-2.0
func WithTarget(ctx context.Context, target string) context.Context { return context.WithValue(ctx, targetKey, target) }
WithTarget returns back a new context with the given target. Target is intended to be transport dependent. For http transport, `target` should be a full URL and will be injected into the outbound http request.
WithTarget
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func TargetFrom(ctx context.Context) *url.URL { c := ctx.Value(targetKey) if c != nil { if s, ok := c.(string); ok && s != "" { if target, err := url.Parse(s); err == nil { return target } } } return nil }
TargetFrom looks in the given context and returns `target` as a parsed url if found and valid, otherwise nil.
TargetFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithTopic(ctx context.Context, topic string) context.Context { return context.WithValue(ctx, topicKey, topic) }
WithTopic returns back a new context with the given topic. Topic is intended to be transport dependent. For pubsub transport, `topic` should be a Pub/Sub Topic ID.
WithTopic
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func TopicFrom(ctx context.Context) string { c := ctx.Value(topicKey) if c != nil { if s, ok := c.(string); ok { return s } } return "" }
TopicFrom looks in the given context and returns `topic` as a string if found and valid, otherwise "".
TopicFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesConstantBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyConstant, Period: delay, MaxTries: maxTries, }) }
WithRetriesConstantBackoff returns back a new context with retries parameters using constant backoff strategy. MaxTries is the maximum number for retries and delay is the time interval between retries
WithRetriesConstantBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesLinearBackoff(ctx context.Context, delay time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyLinear, Period: delay, MaxTries: maxTries, }) }
WithRetriesLinearBackoff returns back a new context with retries parameters using linear backoff strategy. MaxTries is the maximum number for retries and delay*tries is the time interval between retries
WithRetriesLinearBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetriesExponentialBackoff(ctx context.Context, period time.Duration, maxTries int) context.Context { return WithRetryParams(ctx, &RetryParams{ Strategy: BackoffStrategyExponential, Period: period, MaxTries: maxTries, }) }
WithRetriesExponentialBackoff returns back a new context with retries parameters using exponential backoff strategy. MaxTries is the maximum number for retries and period is the amount of time to wait, used as `period * 2^retries`.
WithRetriesExponentialBackoff
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func WithRetryParams(ctx context.Context, rp *RetryParams) context.Context { return context.WithValue(ctx, retriesKey, rp) }
WithRetryParams returns back a new context with retries parameters.
WithRetryParams
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func RetriesFrom(ctx context.Context) *RetryParams { c := ctx.Value(retriesKey) if c != nil { if s, ok := c.(*RetryParams); ok { return s } } return &DefaultRetryParams }
RetriesFrom looks in the given context and returns the retries parameters if found. Otherwise returns the default retries configuration (ie. no retries).
RetriesFrom
go
cloudevents/sdk-go
v2/context/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/context.go
Apache-2.0
func ValuesDelegating(child, parent context.Context) context.Context { return &valuesDelegating{ Context: child, parent: parent, } }
ValuesDelegating wraps a child and parent context. It will perform Value() lookups first on the child, and then fall back to the child. All other calls go solely to the child context.
ValuesDelegating
go
cloudevents/sdk-go
v2/context/delegating.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/delegating.go
Apache-2.0
func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { if logger == nil { return context.WithValue(ctx, loggerKey, fallbackLogger) } return context.WithValue(ctx, loggerKey, logger) }
WithLogger returns a new context with the logger injected into the given context.
WithLogger
go
cloudevents/sdk-go
v2/context/logger.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/logger.go
Apache-2.0
func LoggerFrom(ctx context.Context) *zap.SugaredLogger { l := ctx.Value(loggerKey) if l != nil { if logger, ok := l.(*zap.SugaredLogger); ok { return logger } } return fallbackLogger }
LoggerFrom returns the logger stored in context.
LoggerFrom
go
cloudevents/sdk-go
v2/context/logger.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/logger.go
Apache-2.0
func (r *RetryParams) BackoffFor(tries int) time.Duration { switch r.Strategy { case BackoffStrategyConstant: return r.Period case BackoffStrategyLinear: return r.Period * time.Duration(tries) case BackoffStrategyExponential: exp := math.Exp2(float64(tries)) return r.Period * time.Duration(exp) case Backof...
BackoffFor tries will return the time duration that should be used for this current try count. `tries` is assumed to be the number of times the caller has already retried.
BackoffFor
go
cloudevents/sdk-go
v2/context/retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/retry.go
Apache-2.0
func (r *RetryParams) Backoff(ctx context.Context, tries int) error { if tries > r.MaxTries { return errors.New("too many retries") } ticker := time.NewTicker(r.BackoffFor(tries)) select { case <-ctx.Done(): ticker.Stop() return errors.New("context has been cancelled") case <-ticker.C: ticker.Stop() } r...
Backoff is a blocking call to wait for the correct amount of time for the retry. `tries` is assumed to be the number of times the caller has already retried.
Backoff
go
cloudevents/sdk-go
v2/context/retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/context/retry.go
Apache-2.0
func isJSON(contentType string) bool { switch contentType { case ApplicationJSON, TextJSON, ApplicationCloudEventsJSON, ApplicationCloudEventsBatchJSON: return true case "": return true // Empty content type assumes json default: return false } }
isJSON returns true if the content type is a JSON type.
isJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationJSON() *string { a := ApplicationJSON return &a }
StringOfApplicationJSON returns a string pointer to "application/json"
StringOfApplicationJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationXML() *string { a := ApplicationXML return &a }
StringOfApplicationXML returns a string pointer to "application/xml"
StringOfApplicationXML
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfTextPlain() *string { a := TextPlain return &a }
StringOfTextPlain returns a string pointer to "text/plain"
StringOfTextPlain
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationCloudEventsJSON() *string { a := ApplicationCloudEventsJSON return &a }
StringOfApplicationCloudEventsJSON returns a string pointer to "application/cloudevents+json"
StringOfApplicationCloudEventsJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func StringOfApplicationCloudEventsBatchJSON() *string { a := ApplicationCloudEventsBatchJSON return &a }
StringOfApplicationCloudEventsBatchJSON returns a string pointer to "application/cloudevents-batch+json"
StringOfApplicationCloudEventsBatchJSON
go
cloudevents/sdk-go
v2/event/content_type.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/content_type.go
Apache-2.0
func New(version ...string) Event { specVersion := defaultEventVersion if len(version) >= 1 { specVersion = version[0] } e := &Event{} e.SetSpecVersion(specVersion) return *e }
New returns a new Event, an optional version can be passed to change the default spec version from 1.0 to the provided version.
New
go
cloudevents/sdk-go
v2/event/event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event.go
Apache-2.0
func (e Event) ExtensionAs(name string, obj interface{}) error { return e.Context.ExtensionAs(name, obj) }
ExtensionAs is deprecated: access extensions directly via the e.Extensions() map. Use functions in the types package to convert extension values. For example replace this: var i int err := e.ExtensionAs("foo", &i) With this: i, err := types.ToInteger(e.Extensions["foo"])
ExtensionAs
go
cloudevents/sdk-go
v2/event/event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event.go
Apache-2.0
func (e Event) String() string { b := strings.Builder{} b.WriteString(e.Context.String()) if e.DataEncoded != nil { if e.DataBase64 { b.WriteString("Data (binary),\n ") } else { b.WriteString("Data,\n ") } switch e.DataMediaType() { case ApplicationJSON: var prettyJSON bytes.Buffer err := j...
String returns a pretty-printed representation of the Event.
String
go
cloudevents/sdk-go
v2/event/event.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event.go
Apache-2.0
func (ec *EventContextV03) SetExtension(name string, value interface{}) error { if ec.Extensions == nil { ec.Extensions = make(map[string]interface{}) } if _, ok := specV03Attributes[strings.ToLower(name)]; ok { return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", nam...
SetExtension adds the extension 'name' with value 'value' to the CloudEvents context. This function fails if the name uses a reserved event context key.
SetExtension
go
cloudevents/sdk-go
v2/event/eventcontext_v03.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/eventcontext_v03.go
Apache-2.0
func (ec *EventContextV1) SetExtension(name string, value interface{}) error { if err := validateExtensionName(name); err != nil { return err } if _, ok := specV1Attributes[strings.ToLower(name)]; ok { return fmt.Errorf("bad key %q: CloudEvents spec attribute MUST NOT be overwritten by extension", name) } na...
SetExtension adds the extension 'name' with value 'value' to the CloudEvents context. This function fails if the name doesn't respect the regex ^[a-zA-Z0-9]+$ or if the name uses a reserved event context key.
SetExtension
go
cloudevents/sdk-go
v2/event/eventcontext_v1.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/eventcontext_v1.go
Apache-2.0
func (ec EventContextV1) Validate() ValidationError { errors := map[string]error{} // id // Type: String // Constraints: // REQUIRED // MUST be a non-empty string // MUST be unique within the scope of the producer id := strings.TrimSpace(ec.ID) if id == "" { errors["id"] = fmt.Errorf("MUST be a non-empty...
Validate returns errors based on requirements from the CloudEvents spec. For more details, see https://github.com/cloudevents/spec/blob/v1.0/spec.md.
Validate
go
cloudevents/sdk-go
v2/event/eventcontext_v1.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/eventcontext_v1.go
Apache-2.0
func (e *Event) SetData(contentType string, obj interface{}) error { e.SetDataContentType(contentType) if e.SpecVersion() != CloudEventsVersionV1 { return e.legacySetData(obj) } // Version 1.0 and above. switch obj := obj.(type) { case []byte: e.DataEncoded = obj e.DataBase64 = true default: data, err ...
SetData encodes the given payload with the given content type. If the provided payload is a byte array, when marshalled to json it will be encoded as base64. If the provided payload is different from byte array, datacodec.Encode is invoked to attempt a marshalling to byte array.
SetData
go
cloudevents/sdk-go
v2/event/event_data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_data.go
Apache-2.0
func (e *Event) legacySetData(obj interface{}) error { data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) if err != nil { return err } if e.DeprecatedDataContentEncoding() == Base64 { buf := make([]byte, base64.StdEncoding.EncodedLen(len(data))) base64.StdEncoding.Encode(buf, data) ...
Deprecated: Delete when we do not have to support Spec v0.3.
legacySetData
go
cloudevents/sdk-go
v2/event/event_data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_data.go
Apache-2.0
func (e Event) DataAs(obj interface{}) error { data := e.Data() if len(data) == 0 { // No data. return nil } if e.SpecVersion() != CloudEventsVersionV1 { var err error if data, err = e.legacyConvertData(data); err != nil { return err } } return datacodec.Decode(context.Background(), e.DataMediaTyp...
DataAs attempts to populate the provided data object with the event payload. obj should be a pointer type.
DataAs
go
cloudevents/sdk-go
v2/event/event_data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_data.go
Apache-2.0
func WriteJson(in *Event, writer io.Writer) error { stream := jsoniter.ConfigFastest.BorrowStream(writer) defer jsoniter.ConfigFastest.ReturnStream(stream) stream.WriteObjectStart() var ext map[string]interface{} var dct *string var isBase64 bool // Write the context (without the extensions) switch eventConte...
WriteJson writes the in event in the provided writer. Note: this function assumes the input event is valid.
WriteJson
go
cloudevents/sdk-go
v2/event/event_marshal.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_marshal.go
Apache-2.0
func (e Event) DataMediaType() string { if e.Context != nil { mediaType, _ := e.Context.GetDataMediaType() return mediaType } return "" }
DataMediaType returns the parsed DataMediaType of the event. If parsing fails, the empty string is returned. To retrieve the parsing error, use `Context.GetDataMediaType` instead.
DataMediaType
go
cloudevents/sdk-go
v2/event/event_reader.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_reader.go
Apache-2.0
func TestEventRW_Corrected_Source(t *testing.T) { testCases := map[string]ReadWriteTest{ "corrected v03": { event: event.New("0.3"), set: "%|http://good", want: "", corrected: "http://good", wantErr: "invalid URL escape", }, "corrected v1": { event: event.New("1.0"), set...
Set will be split on pipe, set1|set2
TestEventRW_Corrected_Source
go
cloudevents/sdk-go
v2/event/event_reader_writer_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_reader_writer_test.go
Apache-2.0
func TestExtensionAs(t *testing.T) { now := types.Timestamp{Time: time.Now()} testCases := map[string]struct { event event.Event extension string want string wantError bool wantErrorMsg string }{ "min v03, no extension": { event: event.Event{ Context: MinEventContextV03(), ...
ExtensionAs is deprecated, replacement is TestExtensions below
TestExtensionAs
go
cloudevents/sdk-go
v2/event/event_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_test.go
Apache-2.0
func readJsonFromIterator(out *Event, iterator *jsoniter.Iterator) error { // Parsing dependency graph: // SpecVersion // ^ ^ // | +--------------+ // + + // All Attributes datacontenttype (and datacontentencoding for v0.3) // (except data...
ReadJson allows you to read the bytes reader as an event
readJsonFromIterator
go
cloudevents/sdk-go
v2/event/event_unmarshal.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_unmarshal.go
Apache-2.0
func (e Event) Validate() error { if e.Context == nil { return ValidationError{"specversion": fmt.Errorf("missing Event.Context")} } errs := map[string]error{} if e.FieldErrors != nil { for k, v := range e.FieldErrors { errs[k] = v } } if fieldErrors := e.Context.Validate(); fieldErrors != nil { for ...
Validate performs a spec based validation on this event. Validation is dependent on the spec version specified in the event context.
Validate
go
cloudevents/sdk-go
v2/event/event_validation.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_validation.go
Apache-2.0
func (e *Event) SetDataContentEncoding(enc string) { if err := e.Context.DeprecatedSetDataContentEncoding(enc); err != nil { e.fieldError("datacontentencoding", err) } else { e.fieldOK("datacontentencoding") } }
SetDataContentEncoding is deprecated. Implements EventWriter.SetDataContentEncoding.
SetDataContentEncoding
go
cloudevents/sdk-go
v2/event/event_writer.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/event_writer.go
Apache-2.0
func AddDecoder(contentType string, fn Decoder) { decoder[contentType] = fn }
AddDecoder registers a decoder for a given content type. The codecs will use these to decode the data payload from a cloudevent.Event object.
AddDecoder
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func AddStructuredSuffixDecoder(suffix string, fn Decoder) { ssDecoder[suffix] = fn }
AddStructuredSuffixDecoder registers a decoder for content-types which match the given structured syntax suffix as defined by [Structured Syntax Suffixes](https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml). This allows users to register custom decoders for non-standard con...
AddStructuredSuffixDecoder
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func AddEncoder(contentType string, fn Encoder) { encoder[contentType] = fn }
AddEncoder registers an encoder for a given content type. The codecs will use these to encode the data payload for a cloudevent.Event object.
AddEncoder
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func AddStructuredSuffixEncoder(suffix string, fn Encoder) { ssEncoder[suffix] = fn }
AddStructuredSuffixEncoder registers an encoder for content-types which match the given structured syntax suffix as defined by [Structured Syntax Suffixes](https://www.iana.org/assignments/media-type-structured-suffix/media-type-structured-suffix.xhtml). This allows users to register custom encoders for non-standard co...
AddStructuredSuffixEncoder
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func Decode(ctx context.Context, contentType string, in []byte, out interface{}) error { if fn, ok := decoder[contentType]; ok { return fn(ctx, in, out) } if fn, ok := ssDecoder[structuredSuffix(contentType)]; ok { return fn(ctx, in, out) } return fmt.Errorf("[decode] unsupported content type: %q", contentTy...
Decode looks up and invokes the decoder registered for the given content type. An error is returned if no decoder is registered for the given content type.
Decode
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func Encode(ctx context.Context, contentType string, in interface{}) ([]byte, error) { if fn, ok := encoder[contentType]; ok { return fn(ctx, in) } if fn, ok := ssEncoder[structuredSuffix(contentType)]; ok { return fn(ctx, in) } return nil, fmt.Errorf("[encode] unsupported content type: %q", contentType) }
Encode looks up and invokes the encoder registered for the given content type. An error is returned if no encoder is registered for the given content type.
Encode
go
cloudevents/sdk-go
v2/event/datacodec/codec.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/codec.go
Apache-2.0
func Encode(ctx context.Context, in interface{}) ([]byte, error) { if in == nil { return nil, nil } it := reflect.TypeOf(in) switch it.Kind() { case reflect.Slice: if it.Elem().Kind() == reflect.Uint8 { if b, ok := in.([]byte); ok && len(b) > 0 { // check to see if it is a pre-encoded byte string. ...
Encode attempts to json.Marshal `in` into bytes. Encode will inspect `in` and returns `in` unmodified if it is detected that `in` is already a []byte; Or json.Marshal errors.
Encode
go
cloudevents/sdk-go
v2/event/datacodec/json/data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/json/data.go
Apache-2.0
func TestCodecEncode(t *testing.T) { now := time.Now() testCases := map[string]struct { in interface{} want []byte wantErr string }{ "empty": {}, "BadMarshal": { in: BadMarshal{}, wantErr: "json: error calling MarshalJSON for type json_test.BadMarshal: BadMashal Error", }, "already ...
TODO: test for bad []byte input?
TestCodecEncode
go
cloudevents/sdk-go
v2/event/datacodec/json/data_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/json/data_test.go
Apache-2.0
func Decode(_ context.Context, in []byte, out interface{}) error { p, _ := out.(*string) if p == nil { return fmt.Errorf("text.Decode out: want *string, got %T", out) } *p = string(in) return nil }
Text codec converts []byte or string to string and vice-versa.
Decode
go
cloudevents/sdk-go
v2/event/datacodec/text/data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/text/data.go
Apache-2.0
func Encode(ctx context.Context, in interface{}) ([]byte, error) { if b, ok := in.([]byte); ok { // check to see if it is a pre-encoded byte string. if len(b) > 0 && b[0] == byte('"') { return b, nil } } return xml.Marshal(in) }
Encode attempts to xml.Marshal `in` into bytes. Encode will inspect `in` and returns `in` unmodified if it is detected that `in` is already a []byte; Or xml.Marshal errors.
Encode
go
cloudevents/sdk-go
v2/event/datacodec/xml/data.go
https://github.com/cloudevents/sdk-go/blob/master/v2/event/datacodec/xml/data.go
Apache-2.0
func AddDataRefExtension(e *event.Event, dataRef string) error { if _, err := url.Parse(dataRef); err != nil { return err } e.SetExtension(DataRefExtensionKey, dataRef) return nil }
AddDataRefExtension adds the dataref attribute to the cloudevents context
AddDataRefExtension
go
cloudevents/sdk-go
v2/extensions/dataref_extension.go
https://github.com/cloudevents/sdk-go/blob/master/v2/extensions/dataref_extension.go
Apache-2.0
func GetDataRefExtension(e event.Event) (DataRefExtension, bool) { if dataRefValue, ok := e.Extensions()[DataRefExtensionKey]; ok { dataRefStr, _ := dataRefValue.(string) return DataRefExtension{DataRef: dataRefStr}, true } return DataRefExtension{}, false }
GetDataRefExtension returns any dataref attribute present in the cloudevent event/context and a bool to indicate if it was found. If not found, the DataRefExtension.DataRef value will be ""
GetDataRefExtension
go
cloudevents/sdk-go
v2/extensions/dataref_extension.go
https://github.com/cloudevents/sdk-go/blob/master/v2/extensions/dataref_extension.go
Apache-2.0
func (d DistributedTracingExtension) AddTracingAttributes(e event.EventWriter) { if d.TraceParent != "" { value := reflect.ValueOf(d) typeOf := value.Type() for i := 0; i < value.NumField(); i++ { k := strings.ToLower(typeOf.Field(i).Name) v := value.Field(i).Interface() if k == TraceStateExtension && ...
AddTracingAttributes adds the tracing attributes traceparent and tracestate to the cloudevents context
AddTracingAttributes
go
cloudevents/sdk-go
v2/extensions/distributed_tracing_extension.go
https://github.com/cloudevents/sdk-go/blob/master/v2/extensions/distributed_tracing_extension.go
Apache-2.0
func (e *ErrTransportMessageConversion) IsFatal() bool { return e.fatal }
IsFatal reports if this error should be considered fatal.
IsFatal
go
cloudevents/sdk-go
v2/protocol/error.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/error.go
Apache-2.0
func (e *ErrTransportMessageConversion) Handled() bool { return e.handled }
Handled reports if this error should be considered accepted and no further action.
Handled
go
cloudevents/sdk-go
v2/protocol/error.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/error.go
Apache-2.0
func IsACK(target Result) bool { // special case, nil target also means ACK. if target == nil { return true } return ResultIs(target, ResultACK) }
IsACK true means the recipient acknowledged the event.
IsACK
go
cloudevents/sdk-go
v2/protocol/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/result.go
Apache-2.0
func IsNACK(target Result) bool { return ResultIs(target, ResultNACK) }
IsNACK true means the recipient did not acknowledge the event.
IsNACK
go
cloudevents/sdk-go
v2/protocol/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/result.go
Apache-2.0
func IsUndelivered(target Result) bool { if target == nil { // Short-circuit nil result is ACK. return false } return !ResultIs(target, ResultACK) && !ResultIs(target, ResultNACK) }
IsUndelivered true means the target result is not an ACK/NACK, but some other error unrelated to delivery not from the intended recipient. Likely target is an error that represents some part of the protocol is misconfigured or the event that was attempting to be sent was invalid.
IsUndelivered
go
cloudevents/sdk-go
v2/protocol/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/result.go
Apache-2.0
func NewReceipt(ack bool, messageFmt string, args ...interface{}) Result { return &Receipt{ Err: fmt.Errorf(messageFmt, args...), ACK: ack, } }
NewReceipt returns a fully populated protocol Receipt that should be used as a transport.Result. This type holds the base ACK/NACK results.
NewReceipt
go
cloudevents/sdk-go
v2/protocol/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/result.go
Apache-2.0
func (e *Receipt) Unwrap() error { if e != nil { return errors.Unwrap(e.Err) } return nil }
Unwrap returns the wrapped error if exist or nil
Unwrap
go
cloudevents/sdk-go
v2/protocol/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/result.go
Apache-2.0
func WithRequestDataAtContext(ctx context.Context, r *nethttp.Request) context.Context { if r == nil { return ctx } return context.WithValue(ctx, requestKey{}, &RequestData{ URL: r.URL, Header: r.Header, RemoteAddr: r.RemoteAddr, Host: r.Host, }) }
WithRequestDataAtContext uses the http.Request to add RequestData information to the Context.
WithRequestDataAtContext
go
cloudevents/sdk-go
v2/protocol/http/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/context.go
Apache-2.0
func RequestDataFromContext(ctx context.Context) *RequestData { if req := ctx.Value(requestKey{}); req != nil { return req.(*RequestData) } return nil }
RequestDataFromContext retrieves RequestData from the Context. If not set nil is returned.
RequestDataFromContext
go
cloudevents/sdk-go
v2/protocol/http/context.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/context.go
Apache-2.0
func NewMessage(header nethttp.Header, body io.ReadCloser) *Message { m := Message{Header: header} if body != nil { m.BodyReader = body } if m.format = format.Lookup(header.Get(ContentType)); m.format == nil { m.version = specs.Version(m.Header.Get(specs.PrefixedSpecVersionName())) } return &m }
NewMessage returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods
NewMessage
go
cloudevents/sdk-go
v2/protocol/http/message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/message.go
Apache-2.0
func NewMessageFromHttpRequest(req *nethttp.Request) *Message { if req == nil { return nil } message := NewMessage(req.Header, req.Body) message.ctx = req.Context() return message }
NewMessageFromHttpRequest returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods
NewMessageFromHttpRequest
go
cloudevents/sdk-go
v2/protocol/http/message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/message.go
Apache-2.0
func NewMessageFromHttpResponse(resp *nethttp.Response) *Message { if resp == nil { return nil } msg := NewMessage(resp.Header, resp.Body) return msg }
NewMessageFromHttpResponse returns a binding.Message with header and data. The returned binding.Message *cannot* be read several times. In order to read it more times, buffer it using binding/buffering methods
NewMessageFromHttpResponse
go
cloudevents/sdk-go
v2/protocol/http/message.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/message.go
Apache-2.0