-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainEndless.go
More file actions
85 lines (66 loc) · 1.54 KB
/
Copy pathmainEndless.go
File metadata and controls
85 lines (66 loc) · 1.54 KB
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
81
82
83
84
85
package main
import (
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
"github.com/fvbock/endless"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin"
)
func readTemplate(path string) *template.Template {
dat, _ := ioutil.ReadFile(path)
return template.Must(template.New(path).Parse(string(dat)))
}
func isConnectionLost(c *gin.Context) bool {
done := false
select {
case <-c.Writer.CloseNotify():
done = true
default:
}
return done
}
func handle(r *gin.Engine) {
indexTmplPath := "index.html"
r.SetHTMLTemplate(readTemplate(indexTmplPath))
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, indexTmplPath, map[string]interface{}{})
})
r.GET("/ping", func(c *gin.Context) {
h := c.Writer.Header()
h.Set("Cache-Control", "no-cache")
h.Set("Connection", "keep-alive")
h.Set("Content-Type", "text/event-stream")
h.Set("X-Accel-Buffering", "no")
// data can be a primitive like a string, an integer or a float
ticker := time.NewTicker(1 * time.Second)
for range ticker.C {
if isConnectionLost(c) {
fmt.Println("Event-connection is lost")
return
}
error := sse.Encode(c.Writer, sse.Event{
Event: "message",
Data: strconv.Itoa(int(time.Now().Unix())) + " v1",
})
if error != nil {
log.Println(error)
return
}
c.Writer.Flush()
}
})
}
func main() {
router := gin.Default()
router.Use(cors.Default())
handle(router)
if err := endless.ListenAndServe("localhost:8080", router); err != nil {
log.Fatalln(err)
}
}