Change to SSE from Socket IO

This commit is contained in:
Supan Adit Pratama 2019-10-27 23:34:34 +07:00
parent 7673cf3425
commit 13ae28ff19
2 changed files with 37 additions and 75 deletions

93
main.go
View File

@ -1,93 +1,38 @@
package main
import (
"encoding/json"
"fmt"
"github.com/gin-contrib/cors"
"github.com/gin-contrib/sse"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis"
socketio "github.com/googollee/go-socket.io"
"github.com/supanadit/geosmartsystem/model"
"github.com/supanadit/geosmartsystem/model/tile38"
"log"
)
func main() {
// Tile38
client := redis.NewClient(&redis.Options{
Addr: "localhost:9851",
})
router := gin.Default()
//router.Use(cors.New(cors.Config{
// AllowOrigins: []string{"http://localhost:4200"},
// AllowMethods: []string{"PUT", "PATCH", "POST", "GET"},
// AllowHeaders: []string{"Origin"},
// ExposeHeaders: []string{"Content-Length"},
// AllowWebSockets: true,
// AllowCredentials: true,
// AllowWildcard: true,
//}))
router.Use(cors.Default())
router.GET("/points", func(c *gin.Context) {
data, _ := tile38.FromScan(client, "sales")
c.JSON(200, data)
})
// Socket.IO Start
server, err := socketio.NewServer(nil)
if err != nil {
log.Fatal(err)
}
server.OnConnect("/", func(s socketio.Conn) error {
s.SetContext("")
fmt.Println("Connected:", s.ID())
data, _ := tile38.FromScan(client, "sales")
s.Emit("points", data)
return nil
})
server.OnEvent("/", "set-points", func(s socketio.Conn, msg string) {
r := gin.Default()
r.Use(cors.Default())
r.POST("/set-points", func(c *gin.Context) {
var location model.Location
err = json.Unmarshal([]byte(msg), &location)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(location)
data, err := tile38.GetDataLocation(client, "sales", location.Id)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(data)
}
}
_ = c.BindJSON(&location)
c.Writer.Header().Set("Content-Type", "application/json")
client.Do("SET", location.Type, location.Id, "POINT", location.Lat, location.Lng)
c.JSON(200, gin.H{"status": "ok"})
})
server.OnEvent("/", "bye", func(s socketio.Conn) string {
last := s.Context().(string)
s.Emit("bye", last)
_ = s.Close()
return last
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,
})
server.OnError("/", func(e error) {
fmt.Println("Meet Error:", e)
})
server.OnDisconnect("/", func(s socketio.Conn, msg string) {
fmt.Println("Closed", msg)
})
router.GET("/socket.io/", gin.WrapH(server))
router.POST("/socket.io/", gin.WrapH(server))
router.Handle("WS", "/socket.io/", WebSocketIO(server))
router.Handle("WSS", "/socket.io/", WebSocketIO(server))
router.GET("/ws", func(c *gin.Context) {
server.ServeHTTP(c.Writer, c.Request)
})
go server.Serve()
defer server.Close()
// End Socket.IO
_ = router.Run()
}
func WebSocketIO(server *socketio.Server) gin.HandlerFunc {
return func(c *gin.Context) {
server.ServeHTTP(c.Writer, c.Request)
}
r.Static("/public", "./public")
_ = r.Run()
}

17
public/index.html Normal file
View File

@ -0,0 +1,17 @@
<!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>