Skip to content

Commit 50f1453

Browse files
committed
add NewEvent constructor with class name
1 parent 18de984 commit 50f1453

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

event.go

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,30 @@ type Event struct {
2121
body []byte
2222
}
2323

24-
// NewEvent returns a new Event with the given headers and body.
25-
func NewEvent(headers map[string]string, body []byte) Event {
24+
// NewEvent returns a new Event with the given name, headers and body.
25+
//
26+
// It panics if the name is empty or if the name is CUSTOM without the Event-Subclass name.
27+
func NewEvent(name string, headers map[string]string, body []byte) Event {
28+
//nolint:forbidigo
29+
switch name {
30+
case "":
31+
panic("event name cannot be empty")
32+
case "CUSTOM":
33+
panic("event name cannot be CUSTOM without Event-Subclass name")
34+
}
35+
36+
if name, ok := isCustomEvent(name); ok {
37+
headers["Event-Name"] = "CUSTOM"
38+
headers["Event-Subclass"] = name
39+
} else {
40+
headers["Event-Name"] = name
41+
delete(headers, "Event-Subclass")
42+
}
43+
44+
if _, ok := headers["Content-Length"]; !ok {
45+
delete(headers, "Content-Length")
46+
}
47+
2648
return Event{
2749
headers: headers,
2850
body: body,

events.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,14 @@ func buildEventNamesCmd(names ...string) string {
171171

172172
return native.String()
173173
}
174+
175+
// isCustomEvent checks if the given event name is a custom event.
176+
func isCustomEvent(name string) (string, bool) {
177+
if name, ok := strings.CutPrefix(name, "CUSTOM "); ok {
178+
return name, true
179+
}
180+
181+
_, ok := eventNames[name]
182+
183+
return name, !ok
184+
}

0 commit comments

Comments
 (0)