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 .idea
.vscode .vscode
/public
!/public/.gitkeep

25
main.go
View File

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