-
Notifications
You must be signed in to change notification settings - Fork 0
/
sse.go
60 lines (51 loc) · 1.24 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
package main
import (
"bufio"
"bytes"
"fmt"
"time"
"github.com/valyala/fasthttp"
)
func handler(ctx *fasthttp.RequestCtx) {
if string(ctx.Method()) == "OPTIONS" {
ctx.WriteString("ok")
return
}
if bytes.HasPrefix(ctx.Path(), []byte("/source")) {
ctx.SetContentType("text/event-stream")
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
ctx.Response.Header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
ctx.Response.Header.Set("Access-Control-Allow-Headers", "Content-Type,Accept")
ctx.SetBodyStreamWriter(func(w *bufio.Writer) {
for {
w.Write([]byte(fmt.Sprintf("data: %s\n\n", time.Now())))
if err := w.Flush(); err != nil {
println("client disconnected")
return
}
time.Sleep(time.Second)
}
})
} else {
ctx.SetContentType("text/html")
ctx.SetBody([]byte(`
<!doctype html>
<body>
<div id=d></div>
<script>
var source = new EventSource('http://localhost:8080/source');
source.onmessage = function(e) {
document.getElementById('d').innerHTML = e.data;
};
</script>
`))
}
}
func main() {
server := &fasthttp.Server{
Handler: handler,
}
if err := server.ListenAndServe(":8080"); err != nil {
panic(err)
}
}