-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
event.go
39 lines (30 loc) · 943 Bytes
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package mercure
import (
"fmt"
"strings"
)
// Event is the actual Server Sent Event that will be dispatched.
type Event struct {
// The updates' data, encoded in the sever-sent event format: every line starts with the string "data: "
// https://www.w3.org/TR/eventsource/#dispatchMessage
Data string
// The globally unique identifier corresponding to update
ID string
// The event type, will be attached to the "event" field
Type string
// The reconnection time
Retry uint64
}
// String serializes the event in a "text/event-stream" representation.
func (e *Event) String() string {
var b strings.Builder
if e.Type != "" {
_, _ = fmt.Fprintf(&b, "event: %s\n", e.Type)
}
if e.Retry != 0 {
_, _ = fmt.Fprintf(&b, "retry: %d\n", e.Retry)
}
r := strings.NewReplacer("\r\n", "\ndata: ", "\r", "\ndata: ", "\n", "\ndata: ")
_, _ = fmt.Fprintf(&b, "id: %s\ndata: %s\n\n", e.ID, r.Replace(e.Data))
return b.String()
}