forked from makeless/makeless-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event.go
54 lines (45 loc) · 1.29 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
package makeless_go
import (
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin"
"github.com/makeless/makeless-go/http"
)
func (makeless *Makeless) events(http makeless_go_http.Http) error {
http.GetRouter().GetEngine().GET(
"/api/auth/event",
http.GetAuthenticator().GetMiddleware().MiddlewareFunc(),
func(c *gin.Context) {
userId := http.GetAuthenticator().GetAuthUserId(c)
w := c.Writer
h := w.Header()
h.Set("Content-Type", "text/event-stream")
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("X-Accel-Buffering", "no")
clientId := http.GetEvent().NewClientId()
http.GetEvent().Subscribe(userId, clientId)
go func() {
if err := http.GetEvent().Trigger(userId, "makeless", "subscribed", clientId); err != nil {
http.GetEvent().TriggerError(err)
}
}()
for {
select {
case event := <-http.GetEvent().Listen(userId, clientId):
if err := sse.Encode(w, event); err != nil {
panic(err)
}
w.Flush()
case err := <-http.GetEvent().ListenError():
panic(err)
case <-w.CloseNotify():
http.GetEvent().Unsubscribe(userId, clientId)
if err := http.GetEvent().Trigger(userId, "makeless", "unsubscribed", clientId); err != nil {
panic(err)
}
}
}
},
)
return nil
}