code
stringlengths
22
3.95M
docstring
stringlengths
20
17.8k
func_name
stringlengths
1
472
language
stringclasses
1 value
repo
stringlengths
6
57
path
stringlengths
4
226
url
stringlengths
43
277
license
stringclasses
7 values
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 := json.Indent(&prettyJSON, e.DataEncoded, " ", " ") if err != nil { b.Write(e.DataEncoded) } else { b.Write(prettyJSON.Bytes()) } default: b.Write(e.DataEncoded) } b.WriteString("\n") } return b.String() }
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", name) } if value == nil { delete(ec.Extensions, name) if len(ec.Extensions) == 0 { ec.Extensions = nil } return nil } else { v, err := types.Validate(value) if err == nil { ec.Extensions[name] = v } return err } }
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 EventContextV03) String() string { b := strings.Builder{} b.WriteString("Context Attributes,\n") b.WriteString(" specversion: " + CloudEventsVersionV03 + "\n") b.WriteString(" type: " + ec.Type + "\n") b.WriteString(" source: " + ec.Source.String() + "\n") if ec.Subject != nil { b.WriteString(" subject: " + *ec.Subject + "\n") } b.WriteString(" id: " + ec.ID + "\n") if ec.Time != nil { b.WriteString(" time: " + ec.Time.String() + "\n") } if ec.SchemaURL != nil { b.WriteString(" schemaurl: " + ec.SchemaURL.String() + "\n") } if ec.DataContentType != nil { b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") } if ec.DataContentEncoding != nil { b.WriteString(" datacontentencoding: " + *ec.DataContentEncoding + "\n") } if len(ec.Extensions) > 0 { b.WriteString("Extensions,\n") keys := make([]string, 0, len(ec.Extensions)) for k := range ec.Extensions { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) } } return b.String() }
String returns a pretty-printed representation of the EventContext.
String
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) } name = strings.ToLower(name) if ec.Extensions == nil { ec.Extensions = make(map[string]interface{}) } if value == nil { delete(ec.Extensions, name) if len(ec.Extensions) == 0 { ec.Extensions = nil } return nil } else { v, err := types.Validate(value) // Ensure it's a legal CE attribute value if err == nil { ec.Extensions[name] = v } return err } }
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 string") // no way to test "MUST be unique within the scope of the producer" } // source // Type: URI-reference // Constraints: // REQUIRED // MUST be a non-empty URI-reference // An absolute URI is RECOMMENDED source := strings.TrimSpace(ec.Source.String()) if source == "" { errors["source"] = fmt.Errorf("REQUIRED") } // type // Type: String // Constraints: // REQUIRED // MUST be a non-empty string // SHOULD be prefixed with a reverse-DNS name. The prefixed domain dictates the organization which defines the semantics of this event type. eventType := strings.TrimSpace(ec.Type) if eventType == "" { errors["type"] = fmt.Errorf("MUST be a non-empty string") } // The following attributes are optional but still have validation. // datacontenttype // Type: String per RFC 2046 // Constraints: // OPTIONAL // If present, MUST adhere to the format specified in RFC 2046 if ec.DataContentType != nil { dataContentType := strings.TrimSpace(*ec.DataContentType) if dataContentType == "" { errors["datacontenttype"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 2046") } else { _, _, err := mime.ParseMediaType(dataContentType) if err != nil { errors["datacontenttype"] = fmt.Errorf("failed to parse RFC 2046 media type %w", err) } } } // dataschema // Type: URI // Constraints: // OPTIONAL // If present, MUST adhere to the format specified in RFC 3986 if ec.DataSchema != nil { if !ec.DataSchema.Validate() { errors["dataschema"] = fmt.Errorf("if present, MUST adhere to the format specified in RFC 3986, Section 4.3. Absolute URI") } } // subject // Type: String // Constraints: // OPTIONAL // MUST be a non-empty string if ec.Subject != nil { subject := strings.TrimSpace(*ec.Subject) if subject == "" { errors["subject"] = fmt.Errorf("if present, MUST be a non-empty string") } } // time // Type: Timestamp // Constraints: // OPTIONAL // If present, MUST adhere to the format specified in RFC 3339 // --> no need to test this, no way to set the time without it being valid. if len(errors) > 0 { return errors } return nil }
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 (ec EventContextV1) String() string { b := strings.Builder{} b.WriteString("Context Attributes,\n") b.WriteString(" specversion: " + CloudEventsVersionV1 + "\n") b.WriteString(" type: " + ec.Type + "\n") b.WriteString(" source: " + ec.Source.String() + "\n") if ec.Subject != nil { b.WriteString(" subject: " + *ec.Subject + "\n") } b.WriteString(" id: " + ec.ID + "\n") if ec.Time != nil { b.WriteString(" time: " + ec.Time.String() + "\n") } if ec.DataSchema != nil { b.WriteString(" dataschema: " + ec.DataSchema.String() + "\n") } if ec.DataContentType != nil { b.WriteString(" datacontenttype: " + *ec.DataContentType + "\n") } if len(ec.Extensions) > 0 { b.WriteString("Extensions,\n") keys := make([]string, 0, len(ec.Extensions)) for k := range ec.Extensions { keys = append(keys, k) } sort.Strings(keys) for _, key := range keys { b.WriteString(fmt.Sprintf(" %s: %v\n", key, ec.Extensions[key])) } } return b.String() }
String returns a pretty-printed representation of the EventContext.
String
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 := datacodec.Encode(context.Background(), e.DataMediaType(), obj) if err != nil { return err } e.DataEncoded = data e.DataBase64 = false } return nil }
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) e.DataEncoded = buf e.DataBase64 = false } else { data, err := datacodec.Encode(context.Background(), e.DataMediaType(), obj) if err != nil { return err } e.DataEncoded = data e.DataBase64 = false } return nil }
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.DataMediaType(), data, obj) }
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 eventContext := in.Context.(type) { case *EventContextV03: // Set a bunch of variables we need later ext = eventContext.Extensions dct = eventContext.DataContentType stream.WriteObjectField("specversion") stream.WriteString(CloudEventsVersionV03) stream.WriteMore() stream.WriteObjectField("id") stream.WriteString(eventContext.ID) stream.WriteMore() stream.WriteObjectField("source") stream.WriteString(eventContext.Source.String()) stream.WriteMore() stream.WriteObjectField("type") stream.WriteString(eventContext.Type) if eventContext.Subject != nil { stream.WriteMore() stream.WriteObjectField("subject") stream.WriteString(*eventContext.Subject) } if eventContext.DataContentEncoding != nil { isBase64 = true stream.WriteMore() stream.WriteObjectField("datacontentencoding") stream.WriteString(*eventContext.DataContentEncoding) } if eventContext.DataContentType != nil { stream.WriteMore() stream.WriteObjectField("datacontenttype") stream.WriteString(*eventContext.DataContentType) } if eventContext.SchemaURL != nil { stream.WriteMore() stream.WriteObjectField("schemaurl") stream.WriteString(eventContext.SchemaURL.String()) } if eventContext.Time != nil { stream.WriteMore() stream.WriteObjectField("time") stream.WriteString(eventContext.Time.String()) } case *EventContextV1: // Set a bunch of variables we need later ext = eventContext.Extensions dct = eventContext.DataContentType isBase64 = in.DataBase64 stream.WriteObjectField("specversion") stream.WriteString(CloudEventsVersionV1) stream.WriteMore() stream.WriteObjectField("id") stream.WriteString(eventContext.ID) stream.WriteMore() stream.WriteObjectField("source") stream.WriteString(eventContext.Source.String()) stream.WriteMore() stream.WriteObjectField("type") stream.WriteString(eventContext.Type) if eventContext.Subject != nil { stream.WriteMore() stream.WriteObjectField("subject") stream.WriteString(*eventContext.Subject) } if eventContext.DataContentType != nil { stream.WriteMore() stream.WriteObjectField("datacontenttype") stream.WriteString(*eventContext.DataContentType) } if eventContext.DataSchema != nil { stream.WriteMore() stream.WriteObjectField("dataschema") stream.WriteString(eventContext.DataSchema.String()) } if eventContext.Time != nil { stream.WriteMore() stream.WriteObjectField("time") stream.WriteString(eventContext.Time.String()) } default: return fmt.Errorf("missing event context") } // Let's do a check on the error if stream.Error != nil { return fmt.Errorf("error while writing the event attributes: %w", stream.Error) } // Let's write the body if in.DataEncoded != nil { stream.WriteMore() // We need to figure out the media type first var mediaType string if dct == nil { mediaType = ApplicationJSON } else { // This code is required to extract the media type from the full content type string (which might contain encoding and stuff) contentType := *dct i := strings.IndexRune(contentType, ';') if i == -1 { i = len(contentType) } mediaType = strings.TrimSpace(strings.ToLower(contentType[0:i])) } // If IsJSON and no encoding to base64, we don't need to perform additional steps if isJSON(mediaType) && !isBase64 { stream.WriteObjectField("data") _, err := stream.Write(in.DataEncoded) if err != nil { return fmt.Errorf("error while writing data: %w", err) } } else { if in.Context.GetSpecVersion() == CloudEventsVersionV1 && isBase64 { stream.WriteObjectField("data_base64") } else { stream.WriteObjectField("data") } // At this point of we need to write to base 64 string, or we just need to write the plain string if isBase64 { stream.WriteString(base64.StdEncoding.EncodeToString(in.DataEncoded)) } else { stream.WriteString(string(in.DataEncoded)) } } } // Let's do a check on the error if stream.Error != nil { return fmt.Errorf("error while writing the event data: %w", stream.Error) } // Add extensions in a deterministic predictable order, similar to how Go maps are serialized in a predictable order. extensionNames := make([]string, 0, len(ext)) for extName := range ext { extensionNames = append(extensionNames, extName) } slices.Sort(extensionNames) for _, extName := range extensionNames { stream.WriteMore() stream.WriteObjectField(extName) stream.WriteVal(ext[extName]) } stream.WriteObjectEnd() // Let's do a check on the error if stream.Error != nil { return fmt.Errorf("error while writing the event extensions: %w", stream.Error) } return stream.Flush() }
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) MarshalJSON() ([]byte, error) { var buf bytes.Buffer err := WriteJson(&e, &buf) return buf.Bytes(), err }
MarshalJSON implements a custom json marshal method used when this type is marshaled using json.Marshal.
MarshalJSON
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: "%|http://good", want: "", corrected: "http://good", wantErr: "invalid URL escape", }, } for n, tc := range testCases { t.Run(n, func(t *testing.T) { var got interface{} var err error // Split set on pipe. set := strings.Split(tc.set, "|") // Set tc.event.SetSource(set[0]) got = tc.event.Source() if tc.wantErr != "" { err = event.ValidationError(tc.event.FieldErrors) } validateReaderWriter(t, tc, got, err) // Correct tc.event.SetSource(set[1]) got = tc.event.Source() if tc.wantErr != "" { err = event.ValidationError(tc.event.FieldErrors) } validateReaderWriterCorrected(t, tc, got, err) }) } }
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(), }, extension: "test", wantError: true, wantErrorMsg: `extension "test" does not exist`, }, "full v03, test extension": { event: event.Event{ Context: FullEventContextV03(now), }, extension: "test", want: "extended", }, "full v03, anothertest extension invalid type": { event: event.Event{ Context: FullEventContextV03(now), }, extension: "anothertest", wantError: true, wantErrorMsg: `invalid type for extension "anothertest"`, }, "full v1, test extension": { event: event.Event{ Context: FullEventContextV1(now), }, extension: "test", want: "extended", }, "full v1, anothertest extension invalid type": { event: event.Event{ Context: FullEventContextV1(now), }, extension: "anothertest", wantError: true, wantErrorMsg: `unknown extension type *string`, }, } for n, tc := range testCases { t.Run(n, func(t *testing.T) { var got string err := tc.event.Context.ExtensionAs(tc.extension, &got) if tc.wantError { if err == nil { t.Errorf("expected error %q, got nil", tc.wantErrorMsg) } else { if diff := cmp.Diff(tc.wantErrorMsg, err.Error()); diff != "" { t.Errorf("unexpected (-want, +got) = %v", diff) } } } else { if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("unexpected (-want, +got) = %v", diff) } } }) } }
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 datacontenttype) ^ // | // | // + // Data var state uint8 = 0 var cachedData []byte var ( // Universally parseable fields. id string typ string source types.URIRef subject *string time *types.Timestamp datacontenttype *string extensions = make(map[string]interface{}) // These fields require knowledge about the specversion to be parsed. schemaurl jsoniter.Any datacontentencoding jsoniter.Any dataschema jsoniter.Any dataBase64 jsoniter.Any ) for key := iterator.ReadObject(); key != ""; key = iterator.ReadObject() { // Check if we have some error in our error cache if iterator.Error != nil { return iterator.Error } // We have a key, now we need to figure out what to do // depending on the parsing state // If it's a specversion, trigger state change if key == "specversion" { if checkFlag(state, specVersionV1Flag|specVersionV03Flag) { return fmt.Errorf("specversion was already provided") } sv := iterator.ReadString() // Check proper specversion switch sv { case CloudEventsVersionV1: con := &EventContextV1{ ID: id, Type: typ, Source: source, Subject: subject, Time: time, DataContentType: datacontenttype, } // Add the fields relevant for the version ... if dataschema != nil { var err error con.DataSchema, err = toUriPtr(dataschema) if err != nil { return err } } if dataBase64 != nil { stream := jsoniter.ConfigFastest.BorrowStream(nil) defer jsoniter.ConfigFastest.ReturnStream(stream) dataBase64.WriteTo(stream) cachedData = stream.Buffer() if stream.Error != nil { return stream.Error } appendFlag(&state, dataBase64Flag) } // ... add all remaining fields as extensions. if schemaurl != nil { extensions["schemaurl"] = schemaurl.GetInterface() } if datacontentencoding != nil { extensions["datacontentencoding"] = datacontentencoding.GetInterface() } out.Context = con appendFlag(&state, specVersionV1Flag) case CloudEventsVersionV03: con := &EventContextV03{ ID: id, Type: typ, Source: source, Subject: subject, Time: time, DataContentType: datacontenttype, } var err error // Add the fields relevant for the version ... if schemaurl != nil { con.SchemaURL, err = toUriRefPtr(schemaurl) if err != nil { return err } } if datacontentencoding != nil { con.DataContentEncoding, err = toStrPtr(datacontentencoding) if *con.DataContentEncoding != Base64 { err = ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} } if err != nil { return err } appendFlag(&state, dataBase64Flag) } // ... add all remaining fields as extensions. if dataschema != nil { extensions["dataschema"] = dataschema.GetInterface() } if dataBase64 != nil { extensions["data_base64"] = dataBase64.GetInterface() } out.Context = con appendFlag(&state, specVersionV03Flag) default: return ValidationError{"specversion": errors.New("unknown value: " + sv)} } // Apply all extensions to the context object. for key, val := range extensions { if err := out.Context.SetExtension(key, val); err != nil { return err } } continue } // If no specversion ... if !checkFlag(state, specVersionV03Flag|specVersionV1Flag) { switch key { case "id": id = iterator.ReadString() case "type": typ = iterator.ReadString() case "source": source = readUriRef(iterator) case "subject": subject = readStrPtr(iterator) case "time": time = readTimestamp(iterator) case "datacontenttype": datacontenttype = readStrPtr(iterator) appendFlag(&state, dataContentTypeFlag) case "data": cachedData = iterator.SkipAndReturnBytes() case "data_base64": dataBase64 = iterator.ReadAny() case "dataschema": dataschema = iterator.ReadAny() case "schemaurl": schemaurl = iterator.ReadAny() case "datacontentencoding": datacontentencoding = iterator.ReadAny() default: extensions[key] = iterator.Read() } continue } // From this point downward -> we can assume the event has a context pointer non nil // If it's a datacontenttype, trigger state change if key == "datacontenttype" { if checkFlag(state, dataContentTypeFlag) { return fmt.Errorf("datacontenttype was already provided") } dct := iterator.ReadString() switch ctx := out.Context.(type) { case *EventContextV03: ctx.DataContentType = &dct case *EventContextV1: ctx.DataContentType = &dct } appendFlag(&state, dataContentTypeFlag) continue } // If it's a datacontentencoding and it's v0.3, trigger state change if checkFlag(state, specVersionV03Flag) && key == "datacontentencoding" { if checkFlag(state, dataBase64Flag) { return ValidationError{"datacontentencoding": errors.New("datacontentencoding was specified twice")} } dce := iterator.ReadString() if dce != Base64 { return ValidationError{"datacontentencoding": errors.New("invalid datacontentencoding value, the only allowed value is 'base64'")} } out.Context.(*EventContextV03).DataContentEncoding = &dce appendFlag(&state, dataBase64Flag) continue } // We can parse all attributes, except data. // If it's data or data_base64 and we don't have the attributes to process it, then we cache it // The expanded form of this condition is: // (checkFlag(state, specVersionV1Flag) && !checkFlag(state, dataContentTypeFlag) && (key == "data" || key == "data_base64")) || // (checkFlag(state, specVersionV03Flag) && !(checkFlag(state, dataContentTypeFlag) && checkFlag(state, dataBase64Flag)) && key == "data") if (state&(specVersionV1Flag|dataContentTypeFlag) == specVersionV1Flag && (key == "data" || key == "data_base64")) || ((state&specVersionV03Flag == specVersionV03Flag) && (state&(dataContentTypeFlag|dataBase64Flag) != (dataContentTypeFlag | dataBase64Flag)) && key == "data") { if key == "data_base64" { appendFlag(&state, dataBase64Flag) } cachedData = iterator.SkipAndReturnBytes() continue } // At this point or this value is an attribute (excluding datacontenttype and datacontentencoding), or this value is data and this condition is valid: // (specVersionV1Flag & dataContentTypeFlag) || (specVersionV03Flag & dataContentTypeFlag & dataBase64Flag) switch eventContext := out.Context.(type) { case *EventContextV03: switch key { case "id": eventContext.ID = iterator.ReadString() case "type": eventContext.Type = iterator.ReadString() case "source": eventContext.Source = readUriRef(iterator) case "subject": eventContext.Subject = readStrPtr(iterator) case "time": eventContext.Time = readTimestamp(iterator) case "schemaurl": eventContext.SchemaURL = readUriRefPtr(iterator) case "data": iterator.Error = consumeData(out, checkFlag(state, dataBase64Flag), iterator) default: if eventContext.Extensions == nil { eventContext.Extensions = make(map[string]interface{}, 1) } iterator.Error = eventContext.SetExtension(key, iterator.Read()) } case *EventContextV1: switch key { case "id": eventContext.ID = iterator.ReadString() case "type": eventContext.Type = iterator.ReadString() case "source": eventContext.Source = readUriRef(iterator) case "subject": eventContext.Subject = readStrPtr(iterator) case "time": eventContext.Time = readTimestamp(iterator) case "dataschema": eventContext.DataSchema = readUriPtr(iterator) case "data": iterator.Error = consumeData(out, false, iterator) case "data_base64": iterator.Error = consumeData(out, true, iterator) default: if eventContext.Extensions == nil { eventContext.Extensions = make(map[string]interface{}, 1) } iterator.Error = eventContext.SetExtension(key, iterator.Read()) } } } if state&(specVersionV03Flag|specVersionV1Flag) == 0 { return ValidationError{"specversion": errors.New("no specversion")} } if iterator.Error != nil { return iterator.Error } // If there is a dataToken cached, we always defer at the end the processing // because nor datacontenttype or datacontentencoding are mandatory. if cachedData != nil { return consumeDataAsBytes(out, checkFlag(state, dataBase64Flag), cachedData) } return nil }
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) UnmarshalJSON(b []byte) error { iterator := jsoniter.ConfigFastest.BorrowIterator(b) defer jsoniter.ConfigFastest.ReturnIterator(iterator) return readJsonFromIterator(e, iterator) }
UnmarshalJSON implements the json unmarshal method used when this type is unmarshaled using json.Unmarshal.
UnmarshalJSON
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 k, v := range fieldErrors { errs[k] = v } } if len(errs) > 0 { return ValidationError(errs) } return nil }
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 content types which follow the structured syntax suffix standard (e.g. application/vnd.custom-app+json). Suffix should not include the "+" character, and "json" and "xml" are registered by default.
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 content types which follow the structured syntax suffix standard (e.g. application/vnd.custom-app+json). Suffix should not include the "+" character, and "json" and "xml" are registered by default.
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", contentType) }
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 Decode(ctx context.Context, in []byte, out interface{}) error { if in == nil { return nil } if out == nil { return fmt.Errorf("out is nil") } if err := json.Unmarshal(in, out); err != nil { return fmt.Errorf("[json] found bytes \"%s\", but failed to unmarshal: %s", string(in), err.Error()) } return nil }
Decode takes `in` as []byte. If Event sent the payload as base64, Decoder assumes that `in` is the decoded base64 byte array.
Decode
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 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. if b[0] == byte('"') || b[0] == byte('{') || b[0] == byte('[') { return b, nil } } } } return json.Marshal(in) }
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 encoded object": { in: []byte(`{"a":"apple","b":"banana"}`), want: []byte(`{"a":"apple","b":"banana"}`), }, "already encoded quote": { in: []byte(`"{"a":"apple","b":"banana"}"`), want: []byte(`"{"a":"apple","b":"banana"}"`), }, "already encoded slice": { in: []byte(`["apple","banana"]`), want: []byte(`["apple","banana"]`), }, "simple": { in: map[string]string{ "a": "apple", "b": "banana", }, want: []byte(`{"a":"apple","b":"banana"}`), }, "complex empty": { in: DataExample{}, want: []byte(`{}`), }, "simple array": { in: &[]string{ "apple", "banana", }, want: []byte(`["apple","banana"]`), }, "complex filled": { in: &DataExample{ AnInt: 42, AMap: map[string]map[string]int{ "a": {"1": 1, "2": 2, "3": 3}, "z": {"3": 3, "2": 2, "1": 1}, }, AString: "Hello, World!", ATime: &now, AnArray: []string{"Anne", "Bob", "Chad"}, }, want: func() []byte { data := &DataExample{ AnInt: 42, AMap: map[string]map[string]int{ "a": {"1": 1, "2": 2, "3": 3}, "z": {"3": 3, "2": 2, "1": 1}, }, AString: "Hello, World!", ATime: &now, AnArray: []string{"Anne", "Bob", "Chad"}, } j, err := json.Marshal(data) if err != nil { t.Errorf("failed to marshal test data: %s", err.Error()) } return j }(), }, "object in": { in: &DataExample{ AnInt: 42, }, want: []byte(`{"a":42}`), }, } for n, tc := range testCases { t.Run(n, func(t *testing.T) { got, err := cej.Encode(context.TODO(), tc.in) if diff := cmpErrors(tc.wantErr, err); diff != "" { t.Errorf("unexpected error (-want, +got) = %v", diff) } if tc.want != nil { if diff := cmp.Diff(tc.want, got); diff != "" { t.Errorf("unexpected data (-want, +got) = %v", diff) } } }) } }
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 Decode(ctx context.Context, in []byte, out interface{}) error { if in == nil { return nil } if err := xml.Unmarshal(in, out); err != nil { return fmt.Errorf("[xml] found bytes, but failed to unmarshal: %s %s", err.Error(), string(in)) } return nil }
Decode takes `in` as []byte. If Event sent the payload as base64, Decoder assumes that `in` is the decoded base64 byte array.
Decode
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 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 && v == "" { continue } e.SetExtension(k, v) } } }
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) Is(target error) bool { if o, ok := target.(*Receipt); ok { if e == nil { // Special case nil e as ACK. return o.ACK } return e.ACK == o.ACK } // Allow for wrapped errors. if e != nil { return errors.Is(e.Err, target) } return false }
Is returns if the target error is a Result type checking target.
Is
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) Error() string { if e != nil { return e.Err.Error() } return "" }
Error returns the string that is formed by using the format string with the provided args.
Error
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
func WithTarget(targetUrl string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http target option can not set nil protocol") } targetUrl = strings.TrimSpace(targetUrl) if targetUrl != "" { var err error var target *url.URL target, err = url.Parse(targetUrl) if err != nil { return fmt.Errorf("http target option failed to parse target url: %s", err.Error()) } p.Target = target if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{ Method: nethttp.MethodPost, } } p.RequestTemplate.URL = target return nil } return fmt.Errorf("http target option was empty string") } }
WithTarget sets the outbound recipient of cloudevents when using an HTTP request.
WithTarget
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithHeader(key, value string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http header option can not set nil protocol") } key = strings.TrimSpace(key) if key != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{ Method: nethttp.MethodPost, } } if p.RequestTemplate.Header == nil { p.RequestTemplate.Header = nethttp.Header{} } p.RequestTemplate.Header.Add(key, value) return nil } return fmt.Errorf("http header option was empty string") } }
WithHeader sets an additional default outbound header for all cloudevents when using an HTTP request.
WithHeader
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithHost(value string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http host option can not set nil protocol") } value = strings.TrimSpace(value) if value != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{ Method: nethttp.MethodPost, } } p.RequestTemplate.Host = value return nil } return fmt.Errorf("http host option was empty string") } }
WithHost sets the outbound host header for all cloud events when using an HTTP request
WithHost
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithShutdownTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http shutdown timeout option can not set nil protocol") } p.ShutdownTimeout = timeout return nil } }
WithShutdownTimeout sets the shutdown timeout when the http server is being shutdown.
WithShutdownTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithReadTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http read timeout option can not set nil protocol") } if timeout < 0 { return fmt.Errorf("http read timeout must not be negative") } p.readTimeout = &timeout return nil } }
WithReadTimeout overwrites the default read timeout (600s) of the http server. The specified timeout must not be negative. A timeout of 0 disables read timeouts in the http server.
WithReadTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithWriteTimeout(timeout time.Duration) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http write timeout option can not set nil protocol") } if timeout < 0 { return fmt.Errorf("http write timeout must not be negative") } p.writeTimeout = &timeout return nil } }
WithWriteTimeout overwrites the default write timeout (600s) of the http server. The specified timeout must not be negative. A timeout of 0 disables write timeouts in the http server.
WithWriteTimeout
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithPort(port int) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http port option can not set nil protocol") } if port < 0 || port > 65535 { return fmt.Errorf("http port option was given an invalid port: %d", port) } if err := checkListen(p, "http port option"); err != nil { return err } p.Port = port return nil } }
WithPort sets the listening port for StartReceiver. Only one of WithListener or WithPort is allowed.
WithPort
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithListener(l net.Listener) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http listener option can not set nil protocol") } if err := checkListen(p, "http listener"); err != nil { return err } p.listener.Store(l) return nil } }
WithListener sets the listener for StartReceiver. Only one of WithListener or WithPort is allowed.
WithListener
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithPath(path string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http path option can not set nil protocol") } path = strings.TrimSpace(path) if len(path) == 0 { return fmt.Errorf("http path option was given an invalid path: %q", path) } p.Path = path return nil } }
WithPath sets the path to receive cloudevents on for HTTP transports.
WithPath
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithMethod(method string) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http method option can not set nil protocol") } method = strings.TrimSpace(method) if method != "" { if p.RequestTemplate == nil { p.RequestTemplate = &nethttp.Request{} } p.RequestTemplate.Method = method return nil } return fmt.Errorf("http method option was empty string") } }
WithMethod sets the HTTP verb (GET, POST, PUT, etc.) to use when using an HTTP request.
WithMethod
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithMiddleware(middleware Middleware) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http middleware option can not set nil protocol") } p.middleware = append(p.middleware, middleware) return nil } }
WithMiddleware adds an HTTP middleware to the transport. It may be specified multiple times. Middleware is applied to everything before it. For example `NewClient(WithMiddleware(foo), WithMiddleware(bar))` would result in `bar(foo(original))`.
WithMiddleware
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithRoundTripperDecorator(decorator func(roundTripper nethttp.RoundTripper) nethttp.RoundTripper) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http round tripper option can not set nil protocol") } if p.roundTripper == nil { if p.Client == nil { p.roundTripper = nethttp.DefaultTransport } else { p.roundTripper = p.Client.Transport } } p.roundTripper = decorator(p.roundTripper) return nil } }
WithRoundTripperDecorator decorates the default HTTP RoundTripper chosen.
WithRoundTripperDecorator
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithGetHandlerFunc(fn nethttp.HandlerFunc) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http GET handler func can not set nil protocol") } p.GetHandlerFn = fn return nil } }
WithGetHandlerFunc sets the http GET handler func
WithGetHandlerFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithOptionsHandlerFunc(fn nethttp.HandlerFunc) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("http OPTIONS handler func can not set nil protocol") } p.OptionsHandlerFn = fn return nil } }
WithOptionsHandlerFunc sets the http OPTIONS handler func
WithOptionsHandlerFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithIsRetriableFunc(isRetriable IsRetriable) Option { return func(p *Protocol) error { if p == nil { return fmt.Errorf("isRetriable handler func can not set nil protocol") } if isRetriable == nil { return fmt.Errorf("isRetriable handler can not be nil") } p.isRetriableFunc = isRetriable return nil } }
WithIsRetriableFunc sets the function that gets called to determine if an error should be retried. If not set, the defaultIsRetriableFunc is used.
WithIsRetriableFunc
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func WithRequestDataAtContextMiddleware() Option { return WithMiddleware(func(next nethttp.Handler) nethttp.Handler { return nethttp.HandlerFunc(func(w nethttp.ResponseWriter, r *nethttp.Request) { ctx := WithRequestDataAtContext(r.Context(), r) next.ServeHTTP(w, r.WithContext(ctx)) }) }) }
WithRequestDataAtContextMiddleware adds to the Context RequestData. This enables a user's dispatch handler to inspect HTTP request information by retrieving it from the Context.
WithRequestDataAtContextMiddleware
go
cloudevents/sdk-go
v2/protocol/http/options.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options.go
Apache-2.0
func forceClose(tr *Protocol) { ctx, cancel := context.WithCancel(context.Background()) go func() { _ = tr.OpenInbound(ctx) }() cancel() }
Force a transport to close its server/listener by cancelling StartReceiver
forceClose
go
cloudevents/sdk-go
v2/protocol/http/options_test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/options_test.go
Apache-2.0
func copyHeadersEnsure(from http.Header, to *http.Header) { if len(from) > 0 { if *to == nil { *to = http.Header{} } copyHeaders(from, *to) } }
Ensure to is a non-nil map before copying
copyHeadersEnsure
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) Receive(ctx context.Context) (binding.Message, error) { if ctx == nil { return nil, fmt.Errorf("nil Context") } msg, fn, err := p.Respond(ctx) // No-op the response when finish is invoked. if msg != nil { return binding.WithFinish(msg, func(err error) { if fn != nil { _ = fn(ctx, nil, nil) } }), err } else { return nil, err } }
Receive the next incoming HTTP request as a CloudEvent. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.
Receive
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) Respond(ctx context.Context) (binding.Message, protocol.ResponseFn, error) { if ctx == nil { return nil, nil, fmt.Errorf("nil Context") } select { case in, ok := <-p.incoming: if !ok { return nil, nil, io.EOF } if in.msg == nil { return nil, in.respFn, in.err } return in.msg, in.respFn, in.err case <-ctx.Done(): return nil, nil, io.EOF } }
Respond receives the next incoming HTTP request as a CloudEvent and waits for the response callback to invoked before continuing. Returns non-nil error if the incoming HTTP request fails to parse as a CloudEvent Returns io.EOF if the receiver is closed.
Respond
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) ServeHTTP(rw http.ResponseWriter, req *http.Request) { // always apply limiter first using req context ok, reset, err := p.limiter.Allow(req.Context(), req) if err != nil { p.incoming <- msgErr{msg: nil, err: fmt.Errorf("unable to acquire rate limit token: %w", err)} rw.WriteHeader(http.StatusInternalServerError) return } if !ok { rw.Header().Add("Retry-After", strconv.Itoa(int(reset))) http.Error(rw, "limit exceeded", http.StatusTooManyRequests) return } // Filter the GET style methods: switch req.Method { case http.MethodOptions: if p.OptionsHandlerFn == nil { rw.WriteHeader(http.StatusMethodNotAllowed) return } p.OptionsHandlerFn(rw, req) return case http.MethodGet: if p.GetHandlerFn == nil { rw.WriteHeader(http.StatusMethodNotAllowed) return } p.GetHandlerFn(rw, req) return case http.MethodDelete: if p.DeleteHandlerFn == nil { rw.WriteHeader(http.StatusMethodNotAllowed) return } p.DeleteHandlerFn(rw, req) return } m := NewMessageFromHttpRequest(req) if m == nil { // Should never get here unless ServeHTTP is called directly. p.incoming <- msgErr{msg: nil, err: binding.ErrUnknownEncoding} rw.WriteHeader(http.StatusBadRequest) return // if there was no message, return. } var finishErr error m.OnFinish = func(err error) error { finishErr = err return nil } wg := sync.WaitGroup{} wg.Add(1) var fn protocol.ResponseFn = func(ctx context.Context, respMsg binding.Message, res protocol.Result, transformers ...binding.Transformer) error { // Unblock the ServeHTTP after the reply is written defer func() { wg.Done() }() if finishErr != nil { http.Error(rw, fmt.Sprintf("Cannot forward CloudEvent: %s", finishErr), http.StatusInternalServerError) return finishErr } status := http.StatusOK var errMsg string if res != nil { var result *Result switch { case protocol.ResultAs(res, &result): if result.StatusCode > 100 && result.StatusCode < 600 { status = result.StatusCode } errMsg = fmt.Errorf(result.Format, result.Args...).Error() case !protocol.IsACK(res): // Map client errors to http status code validationError := event.ValidationError{} if errors.As(res, &validationError) { status = http.StatusBadRequest rw.Header().Set("content-type", "text/plain") rw.WriteHeader(status) _, _ = rw.Write([]byte(validationError.Error())) return validationError } else if errors.Is(res, binding.ErrUnknownEncoding) { status = http.StatusUnsupportedMediaType } else { status = http.StatusInternalServerError } } } if respMsg != nil { err := WriteResponseWriter(ctx, respMsg, status, rw, transformers...) return respMsg.Finish(err) } rw.WriteHeader(status) if _, err := rw.Write([]byte(errMsg)); err != nil { return err } return nil } p.incoming <- msgErr{msg: m, respFn: fn} // Send to Request // Block until ResponseFn is invoked wg.Wait() }
ServeHTTP implements http.Handler. Blocks until ResponseFn is invoked.
ServeHTTP
go
cloudevents/sdk-go
v2/protocol/http/protocol.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol.go
Apache-2.0
func (p *Protocol) GetListeningPort() int { if listener := p.listener.Load(); listener != nil { if tcpAddr, ok := listener.(net.Listener).Addr().(*net.TCPAddr); ok { return tcpAddr.Port } } return -1 }
GetListeningPort returns the listening port. Returns -1 if it's not listening.
GetListeningPort
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func (p *Protocol) listen() (net.Listener, error) { if p.listener.Load() == nil { port := 8080 if p.Port != -1 { port = p.Port if port < 0 || port > 65535 { return nil, fmt.Errorf("invalid port %d", port) } } var err error var listener net.Listener if listener, err = net.Listen("tcp", fmt.Sprintf(":%d", port)); err != nil { return nil, err } p.listener.Store(listener) return listener, nil } return p.listener.Load().(net.Listener), nil }
listen if not already listening, update t.Port
listen
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func (p *Protocol) GetPath() string { path := strings.TrimSpace(p.Path) if len(path) > 0 { return path } return "/" // default }
GetPath returns the path the transport is hosted on. If the path is '/', the transport will handle requests on any URI. To discover the true path a request was received on, inspect the context from Receive(cxt, ...) with TransportContextFrom(ctx).
GetPath
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func attachMiddleware(h http.Handler, middleware []Middleware) http.Handler { for _, m := range middleware { h = m(h) } return h }
attachMiddleware attaches the HTTP middleware to the specified handler.
attachMiddleware
go
cloudevents/sdk-go
v2/protocol/http/protocol_lifecycle.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_lifecycle.go
Apache-2.0
func resetBody(req *http.Request, body []byte) { if req == nil || req.Body == nil { return } req.Body = io.NopCloser(bytes.NewReader(body)) // do not modify existing GetBody function if req.GetBody == nil { req.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil } } }
reset body to allow it to be read multiple times, e.g. when retrying http requests
resetBody
go
cloudevents/sdk-go
v2/protocol/http/protocol_retry.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/protocol_retry.go
Apache-2.0
func NewResult(statusCode int, messageFmt string, args ...interface{}) protocol.Result { return &Result{ StatusCode: statusCode, Format: messageFmt, Args: args, } }
NewResult returns a fully populated http Result that should be used as a transport.Result.
NewResult
go
cloudevents/sdk-go
v2/protocol/http/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/result.go
Apache-2.0
func (e *Result) Is(target error) bool { if o, ok := target.(*Result); ok { return e.StatusCode == o.StatusCode } // Special case for nil == ACK if o, ok := target.(*protocol.Receipt); ok { if e == nil && o.ACK { return true } } // Allow for wrapped errors. if e != nil { err := fmt.Errorf(e.Format, e.Args...) return errors.Is(err, target) } return false }
Is returns if the target error is a Result type checking target.
Is
go
cloudevents/sdk-go
v2/protocol/http/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/result.go
Apache-2.0
func (e *Result) Error() string { return fmt.Sprintf("%d: %v", e.StatusCode, fmt.Errorf(e.Format, e.Args...)) }
Error returns the string that is formed by using the format string with the provided args.
Error
go
cloudevents/sdk-go
v2/protocol/http/result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/result.go
Apache-2.0
func NewRetriesResult(result protocol.Result, retries int, startTime time.Time, attempts []protocol.Result) protocol.Result { rr := &RetriesResult{ Result: result, Retries: retries, Duration: time.Since(startTime), } if len(attempts) > 0 { rr.Attempts = attempts } return rr }
NewRetriesResult returns a http RetriesResult that should be used as a transport.Result without retries
NewRetriesResult
go
cloudevents/sdk-go
v2/protocol/http/retries_result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/retries_result.go
Apache-2.0
func (e *RetriesResult) Is(target error) bool { return protocol.ResultIs(e.Result, target) }
Is returns if the target error is a RetriesResult type checking target.
Is
go
cloudevents/sdk-go
v2/protocol/http/retries_result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/retries_result.go
Apache-2.0
func (e *RetriesResult) Error() string { if e.Retries == 0 { return e.Result.Error() } return fmt.Sprintf("%s (%dx)", e.Result.Error(), e.Retries) }
Error returns the string that is formed by using the format string with the provided args.
Error
go
cloudevents/sdk-go
v2/protocol/http/retries_result.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/retries_result.go
Apache-2.0
func NewEventsFromHTTPRequest(req *nethttp.Request) ([]event.Event, error) { msg := NewMessageFromHttpRequest(req) return binding.ToEvents(context.Background(), msg, msg.BodyReader) }
NewEventsFromHTTPRequest returns a batched set of Events from a HTTP Request
NewEventsFromHTTPRequest
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewEventsFromHTTPResponse(resp *nethttp.Response) ([]event.Event, error) { msg := NewMessageFromHttpResponse(resp) return binding.ToEvents(context.Background(), msg, msg.BodyReader) }
NewEventsFromHTTPResponse returns a batched set of Events from a HTTP Response
NewEventsFromHTTPResponse
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewHTTPRequestFromEvent(ctx context.Context, url string, event event.Event) (*nethttp.Request, error) { if err := event.Validate(); err != nil { return nil, err } req, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, nil) if err != nil { return nil, err } if err := WriteRequest(ctx, (*binding.EventMessage)(&event), req); err != nil { return nil, err } return req, nil }
NewHTTPRequestFromEvent creates a http.Request object that can be used with any http.Client for a singular event. This is an HTTP POST action to the provided url.
NewHTTPRequestFromEvent
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func NewHTTPRequestFromEvents(ctx context.Context, url string, events []event.Event) (*nethttp.Request, error) { // Sending batch events is quite straightforward, as there is only JSON format, so a simple implementation. for _, e := range events { if err := e.Validate(); err != nil { return nil, err } } var buffer bytes.Buffer err := json.NewEncoder(&buffer).Encode(events) if err != nil { return nil, err } request, err := nethttp.NewRequestWithContext(ctx, nethttp.MethodPost, url, &buffer) if err != nil { return nil, err } request.Header.Set(ContentType, event.ApplicationCloudEventsBatchJSON) return request, nil }
NewHTTPRequestFromEvents creates a http.Request object that can be used with any http.Client for sending a batched set of events. This is an HTTP POST action to the provided url.
NewHTTPRequestFromEvents
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func IsHTTPBatch(header nethttp.Header) bool { return header.Get(ContentType) == event.ApplicationCloudEventsBatchJSON }
IsHTTPBatch returns if the current http.Request or http.Response is a batch event operation, by checking the header `Content-Type` value.
IsHTTPBatch
go
cloudevents/sdk-go
v2/protocol/http/utility.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/utility.go
Apache-2.0
func WriteRequest(ctx context.Context, m binding.Message, httpRequest *http.Request, transformers ...binding.Transformer) error { structuredWriter := (*httpRequestWriter)(httpRequest) binaryWriter := (*httpRequestWriter)(httpRequest) _, err := binding.Write( ctx, m, structuredWriter, binaryWriter, transformers..., ) return err }
WriteRequest fills the provided httpRequest with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteRequest
go
cloudevents/sdk-go
v2/protocol/http/write_request.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_request.go
Apache-2.0
func (b *httpRequestWriter) setBody(body io.Reader) error { rc, ok := body.(io.ReadCloser) if !ok && body != nil { rc = io.NopCloser(body) } b.Body = rc if body != nil { switch v := body.(type) { case *bytes.Buffer: b.ContentLength = int64(v.Len()) buf := v.Bytes() b.GetBody = func() (io.ReadCloser, error) { r := bytes.NewReader(buf) return io.NopCloser(r), nil } case *bytes.Reader: b.ContentLength = int64(v.Len()) snapshot := *v b.GetBody = func() (io.ReadCloser, error) { r := snapshot return io.NopCloser(&r), nil } case *strings.Reader: b.ContentLength = int64(v.Len()) snapshot := *v b.GetBody = func() (io.ReadCloser, error) { r := snapshot return io.NopCloser(&r), nil } default: // This is where we'd set it to -1 (at least // if body != NoBody) to mean unknown, but // that broke people during the Go 1.8 testing // period. People depend on it being 0 I // guess. Maybe retry later. See Issue 18117. } // For client requests, Request.ContentLength of 0 // means either actually 0, or unknown. The only way // to explicitly say that the ContentLength is zero is // to set the Body to nil. But turns out too much code // depends on NewRequest returning a non-nil Body, // so we use a well-known ReadCloser variable instead // and have the http package also treat that sentinel // variable to mean explicitly zero. if b.GetBody != nil && b.ContentLength == 0 { b.Body = http.NoBody b.GetBody = func() (io.ReadCloser, error) { return http.NoBody, nil } } } return nil }
setBody is a cherry-pick of the implementation in http.NewRequestWithContext
setBody
go
cloudevents/sdk-go
v2/protocol/http/write_request.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_request.go
Apache-2.0
func WriteResponseWriter(ctx context.Context, m binding.Message, status int, rw http.ResponseWriter, transformers ...binding.Transformer) error { if status < 200 || status >= 600 { status = http.StatusOK } writer := &httpResponseWriter{rw: rw, status: status} _, err := binding.Write( ctx, m, writer, writer, transformers..., ) return err }
WriteResponseWriter writes out to the the provided httpResponseWriter with the message m. Using context you can tweak the encoding processing (more details on binding.Write documentation).
WriteResponseWriter
go
cloudevents/sdk-go
v2/protocol/http/write_responsewriter.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/http/write_responsewriter.go
Apache-2.0
func BenchmarkSendReceive(b *testing.B, s protocol.Sender, r protocol.Receiver) { e := test.FullEvent() m := (*binding.EventMessage)(&e) ctx := context.Background() b.ResetTimer() // Don't count setup. for i := 0; i < b.N; i++ { n := 10 // Messages to send async. g := errgroup.Group{} g.Go(func() error { for j := 0; j < n; j++ { if err := s.Send(ctx, m); err != nil { return err } } return nil }) g.Go(func() error { for j := 0; j < n; j++ { m, err := r.Receive(ctx) if err != nil { return err } if err := m.Finish(nil); err != nil { return err } } return nil }) assert.NoError(b, g.Wait()) } }
BenchmarkSendReceive implements a simple send/receive benchmark. Requires a sender and receiver that are connected to each other.
BenchmarkSendReceive
go
cloudevents/sdk-go
v2/protocol/test/benchmark.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/test/benchmark.go
Apache-2.0
func SendReceive(t *testing.T, ctx context.Context, in binding.Message, s protocol.Sender, r protocol.Receiver, outAssert func(binding.Message)) { t.Helper() wg := sync.WaitGroup{} wg.Add(2) // 'wait' is used to ensure that we at least wait until the Receiver // thread starts. We'll then use a 'sleep' (hoping) that waits until // the Receiver itself is ready wait := make(chan bool) go func() { defer wg.Done() wait <- true out, result := r.Receive(ctx) if !protocol.IsACK(result) { require.NoError(t, result) } outAssert(out) finishErr := out.Finish(nil) require.NoError(t, finishErr) }() // Wait until receiver thread starts, and then wait a second to // give the "Receive" call a chance to start (finger's crossed) <-wait time.Sleep(time.Second) go func() { defer wg.Done() mx := sync.Mutex{} finished := false in = binding.WithFinish(in, func(err error) { require.NoError(t, err) mx.Lock() finished = true mx.Unlock() }) result := s.Send(ctx, in) mx.Lock() if !protocol.IsACK(result) { require.NoError(t, result) } mx.Unlock() time.Sleep(5 * time.Millisecond) // let the receiver receive. mx.Lock() require.True(t, finished) mx.Unlock() }() wg.Wait() }
SendReceive does s.Send(in), then it receives the message in r.Receive() and executes outAssert Halt test on error.
SendReceive
go
cloudevents/sdk-go
v2/protocol/test/test.go
https://github.com/cloudevents/sdk-go/blob/master/v2/protocol/test/test.go
Apache-2.0
func AssertEvent(t testing.TB, have event.Event, matchers ...EventMatcher) { err := AllOf(matchers...)(have) if err != nil { t.Fatalf("Error while matching event: %s", err.Error()) } }
AssertEvent is a "matcher like" assertion method to test the properties of an event
AssertEvent
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AssertEventContextEquals(t testing.TB, want event.EventContext, have event.EventContext) { if err := IsContextEqualTo(want)(event.Event{Context: have}); err != nil { t.Fatalf("Error while matching event context: %s", err.Error()) } }
AssertEventContextEquals asserts that two event.Event contexts are equals
AssertEventContextEquals
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AssertEventEquals(t testing.TB, want event.Event, have event.Event) { if err := IsEqualTo(want)(have); err != nil { t.Fatalf("Error while matching event: %s", err.Error()) } }
AssertEventEquals asserts that two event.Event are equals
AssertEventEquals
go
cloudevents/sdk-go
v2/test/event_asserts.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_asserts.go
Apache-2.0
func AnyOf(matchers ...EventMatcher) EventMatcher { return func(have event.Event) error { var errs []error for _, m := range matchers { if err := m(have); err == nil { return nil } else { errs = append(errs, err) } } var sb strings.Builder sb.WriteString("Cannot match any of the provided matchers\n") for i, err := range errs { sb.WriteString(fmt.Sprintf("%d: %s\n", i+1, err)) } return errors.New(sb.String()) } }
AnyOf returns a matcher which match if at least one of the provided matchers matches
AnyOf
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsAttributes(attrs ...spec.Kind) EventMatcher { return func(have event.Event) error { haveVersion := spec.VS.Version(have.SpecVersion()) for _, k := range attrs { attr := haveVersion.AttributeFromKind(k) if isEmpty(attr) { return fmt.Errorf("attribute name '%s' unrecognized", k.String()) } if isEmpty(attr.Get(have.Context)) { return fmt.Errorf("missing or nil/empty attribute '%s'", k.String()) } } return nil } }
ContainsAttributes checks if the event contains at least the provided context attributes
ContainsAttributes
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsExtensions(exts ...string) EventMatcher { return func(have event.Event) error { for _, ext := range exts { if _, ok := have.Extensions()[ext]; !ok { return fmt.Errorf("expecting extension '%s'", ext) } } return nil } }
ContainsExtensions checks if the event contains at least the provided extension names
ContainsExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func ContainsExactlyExtensions(exts ...string) EventMatcher { return func(have event.Event) error { // Copy in a temporary set first extsInEvent := map[string]struct{}{} for k := range have.Extensions() { extsInEvent[k] = struct{}{} } for _, ext := range exts { if _, ok := have.Extensions()[ext]; !ok { return fmt.Errorf("expecting extension '%s'", ext) } else { delete(extsInEvent, ext) } } if len(extsInEvent) != 0 { var unexpectedKeys []string for k := range extsInEvent { unexpectedKeys = append(unexpectedKeys, k) } return fmt.Errorf("not expecting extensions '%v'", unexpectedKeys) } return nil } }
ContainsExactlyExtensions checks if the event contains only the provided extension names and no more
ContainsExactlyExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExactlyAttributesEqualTo(want event.EventContext) EventMatcher { return func(have event.Event) error { if want.GetSpecVersion() != have.SpecVersion() { return fmt.Errorf("not matching specversion: want = '%s', got = '%s'", want.GetSpecVersion(), have.SpecVersion()) } vs := spec.VS.Version(want.GetSpecVersion()) for _, a := range vs.Attributes() { if !reflect.DeepEqual(a.Get(want), a.Get(have.Context)) { return fmt.Errorf("expecting attribute '%s' equal to '%s', got '%s'", a.PrefixedName(), a.Get(want), a.Get(have.Context)) } } return nil } }
HasExactlyAttributesEqualTo checks if the event has exactly the provided spec attributes (excluding extension attributes)
HasExactlyAttributesEqualTo
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExactlyExtensions(ext map[string]interface{}) EventMatcher { return func(have event.Event) error { if diff := cmp.Diff(ext, have.Extensions()); diff != "" { return fmt.Errorf("unexpected extensions (-want, +got) = %v", diff) } return nil } }
HasExactlyExtensions checks if the event contains exactly the provided extensions
HasExactlyExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExtensions(ext map[string]interface{}) EventMatcher { return func(have event.Event) error { for k, v := range ext { if _, ok := have.Extensions()[k]; !ok { return fmt.Errorf("expecting extension '%s'", ext) } if !reflect.DeepEqual(v, have.Extensions()[k]) { return fmt.Errorf("expecting extension '%s' equal to '%s', got '%s'", k, v, have.Extensions()[k]) } } return nil } }
HasExtensions checks if the event contains at least the provided extensions
HasExtensions
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0
func HasExtensionKeys(keys []string) EventMatcher { return func(have event.Event) error { for _, k := range keys { if _, ok := have.Extensions()[k]; !ok { return fmt.Errorf("expecting extension key %q", k) } } return nil } }
HasExtensionKeys checks if the event contains the provided keys from its extensions
HasExtensionKeys
go
cloudevents/sdk-go
v2/test/event_matchers.go
https://github.com/cloudevents/sdk-go/blob/master/v2/test/event_matchers.go
Apache-2.0