-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.go
80 lines (66 loc) · 1.4 KB
/
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
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package sse
import (
"bufio"
"bytes"
"fmt"
"io"
"github.com/palsivertsen/goutils/converters"
)
type Event struct {
Message string
Type string
Comment string
Retry *int
}
func (e *Event) Encode(w io.Writer) {
wrapper := &eventWriter{writer: w}
defer wrapper.end()
if e.Type != "" {
wrapper.writeType(e.Type)
}
if e.Message != "" {
wrapper.writeMessage(e.Message)
}
if e.Comment != "" {
wrapper.writeComment(e.Comment)
}
if e.Retry != nil {
wrapper.writeRetry(*e.Retry)
}
}
type eventWriter struct {
writer io.Writer
written bool
}
func (e *eventWriter) Write(buf []byte) (n int, err error) {
if !e.written {
e.written = true
}
return e.writer.Write(buf)
}
func (e *eventWriter) end() {
if e.written {
fmt.Fprintln(e.writer)
}
}
func (e *eventWriter) writeType(t string) {
e.lineWithTag("event", t)
}
func (e *eventWriter) writeMessage(message string) {
e.linesWithTag("data", bytes.NewBufferString(message))
}
func (e *eventWriter) writeComment(c string) {
e.linesWithTag("", bytes.NewBufferString(c))
}
func (e *eventWriter) writeRetry(retry int) {
e.lineWithTag("retry", converters.Int(retry).ToString())
}
func (e *eventWriter) linesWithTag(tag string, r io.Reader) {
scanner := bufio.NewScanner(r)
for scanner.Scan() {
e.lineWithTag(tag, scanner.Text())
}
}
func (e *eventWriter) lineWithTag(tag string, line string) {
fmt.Fprintf(e, "%s:%s\n", tag, line)
}