forked from alexandrevicenzi/go-sse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
message.go
65 lines (52 loc) · 1.16 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
package sse
import (
"bytes"
"fmt"
"strings"
)
// Message represents a event source message.
type Message struct {
id,
data,
event string
retry int
}
// SimpleMessage creates a simple event source message.
func SimpleMessage(data string) *Message {
return NewMessage("", data, "")
}
// NewMessage creates an event source message.
func NewMessage(id, data, event string) *Message {
return &Message{
id,
data,
event,
0,
}
}
// Buffer formats the message.
func (m *Message) Buffer() *bytes.Buffer {
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 returns the formated message as a string.
func (m *Message) String() string {
return m.Buffer().String()
}
// Bytes returns the formated message as a byte array.
func (m *Message) Bytes() []byte {
return m.Buffer().Bytes()
}