forked from coaidev/coai
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsse.go
80 lines (66 loc) · 1.48 KB
/
sse.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 utils
import (
"fmt"
"io"
"net/http"
"strings"
)
var dataReplacer = strings.NewReplacer(
"\n", "\ndata:",
"\r", "\\r",
)
type StreamEvent struct {
Event string `json:"event"`
Id string `json:"id"`
Data interface{} `json:"data"`
}
type stringWriter interface {
io.Writer
writeString(string) (int, error)
}
type stringWrapper struct {
io.Writer
}
func (w stringWrapper) writeString(str string) (int, error) {
return w.Writer.Write([]byte(str))
}
func checkWriter(writer io.Writer) stringWriter {
if w, ok := writer.(stringWriter); ok {
return w
} else {
return stringWrapper{writer}
}
}
func encode(writer io.Writer, event StreamEvent) error {
w := checkWriter(writer)
return writeData(w, event.Data)
}
func writeData(w stringWriter, data interface{}) error {
dataReplacer.WriteString(w, fmt.Sprint(data))
if strings.HasPrefix(data.(string), "data") {
w.writeString("\n\n")
}
return nil
}
func (r StreamEvent) Render(w http.ResponseWriter) error {
r.WriteContentType(w)
return encode(w, r)
}
func (r StreamEvent) WriteContentType(w http.ResponseWriter) {
header := w.Header()
header["Content-Type"] = []string{"text/event-stream"}
if _, exist := header["Cache-Control"]; !exist {
header["Cache-Control"] = []string{"no-cache"}
}
}
func NewEvent(data interface{}) StreamEvent {
chunk := Marshal(data)
return StreamEvent{
Data: fmt.Sprintf("data: %s", chunk),
}
}
func NewEndEvent() StreamEvent {
return StreamEvent{
Data: "data: [DONE]",
}
}