2015-05-12 17:23:54 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"math/rand"
|
|
|
|
|
|
|
|
"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 10:15:43 +00:00
|
|
|
roomid := c.Param("roomid")
|
2015-05-12 17:23:54 +00: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 10:15:43 +00:00
|
|
|
roomid := c.Param("roomid")
|
2015-05-12 17:23:54 +00:00
|
|
|
userid := fmt.Sprint(rand.Int31())
|
|
|
|
c.HTML(200, "chat_room", gin.H{
|
|
|
|
"roomid": roomid,
|
|
|
|
"userid": userid,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func roomPOST(c *gin.Context) {
|
2015-05-26 10:15:43 +00:00
|
|
|
roomid := c.Param("roomid")
|
|
|
|
userid := c.PostForm("user")
|
|
|
|
message := c.PostForm("message")
|
2015-05-12 17:23:54 +00:00
|
|
|
room(roomid).Submit(userid + ": " + message)
|
|
|
|
|
|
|
|
c.JSON(200, gin.H{
|
|
|
|
"status": "success",
|
|
|
|
"message": message,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func roomDELETE(c *gin.Context) {
|
2015-05-26 10:15:43 +00:00
|
|
|
roomid := c.Param("roomid")
|
2015-05-12 17:23:54 +00:00
|
|
|
deleteBroadcast(roomid)
|
|
|
|
}
|