gin/examples/realtime-advanced/main.go

99 lines
1.9 KiB
Go
Raw Normal View History

2015-05-13 03:35:16 +03:00
package main
import (
2015-05-13 17:44:44 +03:00
"fmt"
2015-05-13 03:35:16 +03:00
"io"
2015-05-13 17:44:44 +03:00
"runtime"
2015-05-13 03:35:16 +03:00
"time"
"github.com/gin-gonic/gin"
2015-05-13 17:44:44 +03:00
"github.com/manucorporat/stats"
2015-05-13 03:35:16 +03:00
)
2015-05-13 17:44:44 +03:00
var messages = stats.New()
2015-05-13 03:35:16 +03:00
func main() {
2015-05-13 17:44:44 +03:00
nuCPU := runtime.NumCPU()
runtime.GOMAXPROCS(nuCPU)
fmt.Printf("Running with %d CPUs\n", nuCPU)
gin.SetMode(gin.ReleaseMode)
2015-05-13 04:19:44 +03:00
router := gin.New()
2015-05-13 04:45:17 +03:00
router.Use(ratelimit, gin.Recovery(), gin.Logger())
2015-05-13 04:19:44 +03:00
2015-05-13 03:35:16 +03:00
router.LoadHTMLGlob("resources/*.templ.html")
router.Static("/static", "resources/static")
router.GET("/", index)
router.GET("/room/:roomid", roomGET)
router.POST("/room/:roomid", roomPOST)
//router.DELETE("/room/:roomid", roomDELETE)
router.GET("/stream/:roomid", streamRoom)
2015-05-13 17:44:44 +03:00
router.Run("127.0.0.1:8080")
2015-05-13 03:35:16 +03:00
}
func index(c *gin.Context) {
c.Redirect(301, "/room/hn")
}
func roomGET(c *gin.Context) {
roomid := c.ParamValue("roomid")
userid := c.FormValue("nick")
2015-05-13 17:44:44 +03:00
if len(userid) > 13 {
userid = userid[0:12] + "..."
}
2015-05-13 03:35:16 +03:00
c.HTML(200, "room_login.templ.html", gin.H{
"roomid": roomid,
"nick": userid,
"timestamp": time.Now().Unix(),
})
}
func roomPOST(c *gin.Context) {
roomid := c.ParamValue("roomid")
nick := c.FormValue("nick")
message := c.PostFormValue("message")
2015-05-13 17:44:44 +03:00
if len(message) > 200 || len(nick) > 13 {
2015-05-13 03:35:16 +03:00
c.JSON(400, gin.H{
"status": "failed",
"error": "the message or nickname is too long",
})
return
}
post := gin.H{
"nick": nick,
"message": message,
}
2015-05-13 17:44:44 +03:00
messages.Add("inbound", 1)
2015-05-13 03:35:16 +03:00
room(roomid).Submit(post)
c.JSON(200, post)
}
func roomDELETE(c *gin.Context) {
roomid := c.ParamValue("roomid")
deleteBroadcast(roomid)
}
func streamRoom(c *gin.Context) {
roomid := c.ParamValue("roomid")
listener := openListener(roomid)
ticker := time.NewTicker(1 * time.Second)
defer closeListener(roomid, listener)
defer ticker.Stop()
c.Stream(func(w io.Writer) bool {
select {
case msg := <-listener:
2015-05-13 17:44:44 +03:00
messages.Add("outbound", 1)
2015-05-13 03:35:16 +03:00
c.SSEvent("message", msg)
case <-ticker.C:
c.SSEvent("stats", Stats())
}
return true
})
}