gin/examples/realtime-chat/main.go

60 lines
1.1 KiB
Go
Raw Normal View History

2015-05-12 20:23:54 +03:00
package main
import (
"fmt"
"io"
"math/rand"
"net/http"
2015-05-12 20:23:54 +03:00
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.SetHTMLTemplate(html)
router.GET("/room/:roomid", roomGET)
router.POST("/room/:roomid", roomPOST)
router.DELETE("/room/:roomid", roomDELETE)
router.GET("/stream/:roomid", stream)
router.Run(":8080")
}
func stream(c *gin.Context) {
2015-05-26 13:15:43 +03:00
roomid := c.Param("roomid")
2015-05-12 20:23:54 +03:00
listener := openListener(roomid)
defer closeListener(roomid, listener)
c.Stream(func(w io.Writer) bool {
c.SSEvent("message", <-listener)
return true
})
}
func roomGET(c *gin.Context) {
2015-05-26 13:15:43 +03:00
roomid := c.Param("roomid")
2015-05-12 20:23:54 +03:00
userid := fmt.Sprint(rand.Int31())
c.HTML(http.StatusOK, "chat_room", gin.H{
2015-05-12 20:23:54 +03:00
"roomid": roomid,
"userid": userid,
})
}
func roomPOST(c *gin.Context) {
2015-05-26 13:15:43 +03:00
roomid := c.Param("roomid")
userid := c.PostForm("user")
message := c.PostForm("message")
2015-05-12 20:23:54 +03:00
room(roomid).Submit(userid + ": " + message)
c.JSON(http.StatusOK, gin.H{
2015-05-12 20:23:54 +03:00
"status": "success",
"message": message,
})
}
func roomDELETE(c *gin.Context) {
2015-05-26 13:15:43 +03:00
roomid := c.Param("roomid")
2015-05-12 20:23:54 +03:00
deleteBroadcast(roomid)
}