forked from alexandrevicenzi/go-sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
52 lines (41 loc) · 819 Bytes
/
message.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
40
41
42
43
44
45
46
47
48
49
50
51
52
package sse
import (
"bytes"
"fmt"
"strings"
)
// Message represents a event source message.
type Message struct {
id,
data,
event string
retry int
}
func SimpleMessage(data string) *Message {
return NewMessage("", data, "")
}
func NewMessage(id, data, event string) *Message {
return &Message{
id,
data,
event,
0,
}
}
func (m *Message) String() string {
var buffer bytes.Buffer
if len(m.id) > 0 {
buffer.WriteString(fmt.Sprintf("id: %s\n", m.id))
}
if m.retry > 0 {
buffer.WriteString(fmt.Sprintf("retry: %d\n", m.retry))
}
if len(m.event) > 0 {
buffer.WriteString(fmt.Sprintf("event: %s\n", m.event))
}
if len(m.data) > 0 {
buffer.WriteString(fmt.Sprintf("data: %s\n", strings.Replace(m.data, "\n", "\ndata: ", -1)))
}
buffer.WriteString("\n")
return buffer.String()
}