Support Request without SSE or SSE for endpoint /stream

This commit is contained in:
Supan Adit Pratama 2019-10-31 20:29:44 +07:00
parent 383aa5b30f
commit f5d2feaa09
5 changed files with 21 additions and 27 deletions

4
.gitignore vendored
View File

@ -1,2 +1,6 @@
.idea
.vscode
/public
!/public/.gitkeep

25
main.go
View File

@ -7,6 +7,7 @@ import (
"github.com/go-redis/redis"
"github.com/supanadit/geosmartsystem/model"
"github.com/supanadit/geosmartsystem/model/tile38"
"net/http"
)
func main() {
@ -23,15 +24,21 @@ func main() {
c.JSON(200, gin.H{"status": "ok"})
})
r.GET("/stream", func(c *gin.Context) {
writer := c.Writer
writer.Header().Set("Content-Type", "text/event-stream")
writer.Header().Set("Cache-Control", "no-cache")
writer.Header().Set("Connection", "keep-alive")
data, _ := tile38.FromScan(client, "sales")
_ = sse.Encode(writer, sse.Event{
Event: "message",
Data: data,
})
w := c.Writer
t := c.DefaultQuery("type", "user")
r := c.DefaultQuery("request", "")
data, _ := tile38.FromScan(client, t)
if r == "sse" {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
_ = sse.Encode(w, sse.Event{
Event: "message",
Data: data,
})
} else {
c.JSON(http.StatusOK, data)
}
})
r.Static("/public", "./public")
_ = r.Run()

0
public/.gitkeep Normal file
View File

View File

@ -1,17 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<p id="test"></p>
<body>
<script>
const id = document.getElementById("test");
const stream = new EventSource("/stream");
stream.onmessage = function (event) {
id.innerText = event.data
};
</script>
</body>
</html>