Skip to content

Commit 26ade34

Browse files
matzewduglin
authored andcommitted
Adding a simple dataref extension, similar to the java sdk
Signed-off-by: Matthias Wessendorf <[email protected]> Signed-off-by: Doug Davis <[email protected]>
1 parent 74ac76d commit 26ade34

File tree

2 files changed

+80
-0
lines changed

2 files changed

+80
-0
lines changed

v2/extensions/dataref_extension.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/*
2+
Copyright 2024 The CloudEvents Authors
3+
SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package extensions
7+
8+
import (
9+
"github.com/cloudevents/sdk-go/v2/event"
10+
"net/url"
11+
)
12+
13+
const DataRefExtensionKey = "dataref"
14+
15+
type DataRefExtension struct {
16+
DataRef string `json:"dataref"`
17+
}
18+
19+
func AddDataRefExtension(e *event.Event, dataRef string) error {
20+
if _, err := url.Parse(dataRef); err != nil {
21+
return err
22+
}
23+
e.SetExtension(DataRefExtensionKey, dataRef)
24+
return nil
25+
}
26+
27+
func GetDataRefExtension(e event.Event) (DataRefExtension, bool) {
28+
if dataRefValue, ok := e.Extensions()[DataRefExtensionKey]; ok {
29+
dataRefStr, ok := dataRefValue.(string)
30+
if !ok {
31+
return DataRefExtension{}, false
32+
}
33+
return DataRefExtension{DataRef: dataRefStr}, true
34+
}
35+
return DataRefExtension{}, false
36+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Copyright 2024 The CloudEvents Authors
3+
SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
package extensions
7+
8+
import (
9+
"testing"
10+
11+
"github.com/cloudevents/sdk-go/v2/event"
12+
)
13+
14+
func TestAddDataRefExtension(t *testing.T) {
15+
tests := []struct {
16+
dataref string
17+
pass bool
18+
}{
19+
{"https://example.com/data", true},
20+
{"://invalid-url", false},
21+
}
22+
23+
for _, test := range tests {
24+
e := event.New()
25+
err := AddDataRefExtension(&e, test.dataref)
26+
if test.pass && err != nil {
27+
t.Fatalf("Failed to add DataRefExtension with valid URL(%s): %s",
28+
test.dataref, err)
29+
}
30+
if !test.pass && err == nil {
31+
t.Fatalf("Expected not to find DataRefExtension (%s), but did",
32+
test.dataref)
33+
}
34+
}
35+
}
36+
37+
func TestGetDataRefExtensionNotFound(t *testing.T) {
38+
e := event.New()
39+
40+
_, ok := GetDataRefExtension(e)
41+
if ok {
42+
t.Fatal("Expected not to find DataRefExtension, but did")
43+
}
44+
}

0 commit comments

Comments
 (0)