Skip to content

Commit 7099892

Browse files
authored
core: Check for nil event origin (#7047)
* fix: crash - null check on event origin * chore: use accessor instead of property
1 parent 45c9341 commit 7099892

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

caddy.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1104,9 +1104,15 @@ func (e Event) Origin() Module { return e.origin } // Returns the module t
11041104
// CloudEvents spec.
11051105
func (e Event) CloudEvent() CloudEvent {
11061106
dataJSON, _ := json.Marshal(e.Data)
1107+
var source string
1108+
if e.Origin() == nil {
1109+
source = "caddy"
1110+
} else {
1111+
source = string(e.Origin().CaddyModule().ID)
1112+
}
11071113
return CloudEvent{
11081114
ID: e.id.String(),
1109-
Source: e.origin.CaddyModule().String(),
1115+
Source: source,
11101116
SpecVersion: "1.0",
11111117
Type: e.name,
11121118
Time: e.ts,

caddy_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
package caddy
1616

1717
import (
18+
"context"
1819
"testing"
1920
"time"
2021
)
@@ -72,3 +73,21 @@ func TestParseDuration(t *testing.T) {
7273
}
7374
}
7475
}
76+
77+
func TestEvent_CloudEvent_NilOrigin(t *testing.T) {
78+
ctx, _ := NewContext(Context{Context: context.Background()}) // module will be nil by default
79+
event, err := NewEvent(ctx, "started", nil)
80+
if err != nil {
81+
t.Fatalf("NewEvent() error = %v", err)
82+
}
83+
84+
// This should not panic
85+
ce := event.CloudEvent()
86+
87+
if ce.Source != "caddy" {
88+
t.Errorf("Expected CloudEvent Source to be 'caddy', got '%s'", ce.Source)
89+
}
90+
if ce.Type != "started" {
91+
t.Errorf("Expected CloudEvent Type to be 'started', got '%s'", ce.Type)
92+
}
93+
}

0 commit comments

Comments
 (0)