-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainTableflip.go
129 lines (103 loc) · 2.27 KB
/
mainTableflip.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"context"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/cloudflare/tableflip"
"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: time.Now().Unix(),
})
if error != nil {
log.Println(error)
return
}
c.Writer.Flush()
}
})
}
func main() {
router := gin.Default()
router.Use(cors.Default())
handle(router)
upg, err := tableflip.New(tableflip.Options{})
if err != nil {
panic(err)
}
defer upg.Stop()
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGHUP)
for range sig {
err := upg.Upgrade()
if err != nil {
log.Println("Upgrade failed:", err)
continue
}
log.Println("Upgrade succeeded")
}
}()
ln, err := upg.Fds.Listen("tcp", "localhost:8080")
if err != nil {
log.Fatalln("Can't listen:", err)
}
server := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
go server.Serve(ln)
if err := upg.Ready(); err != nil {
panic(err)
}
<-upg.Exit()
time.AfterFunc(30*time.Second, func() {
os.Exit(1)
})
_ = server.Shutdown(context.Background())
}