diff --git a/examples/realtime-advanced/limit.go b/examples/realtime-advanced/limit.go index 5d9ec3b..022c936 100644 --- a/examples/realtime-advanced/limit.go +++ b/examples/realtime-advanced/limit.go @@ -4,17 +4,16 @@ import ( "log" "github.com/gin-gonic/gin" + "github.com/manucorporat/stats" ) -import "github.com/manucorporat/stats" - var ips = stats.New() func ratelimit(c *gin.Context) { ip := c.ClientIP() value := uint64(ips.Add(ip, 1)) - if value >= 400 { - if value%400 == 0 { + if value >= 1000 { + if value%1000 == 0 { log.Printf("BlockedIP:%s Requests:%d\n", ip, value) } c.AbortWithStatus(401) diff --git a/examples/realtime-advanced/main.go b/examples/realtime-advanced/main.go index 729f0e8..fb6db71 100644 --- a/examples/realtime-advanced/main.go +++ b/examples/realtime-advanced/main.go @@ -1,13 +1,24 @@ package main import ( + "fmt" "io" + "runtime" "time" "github.com/gin-gonic/gin" + "github.com/manucorporat/stats" ) +var messages = stats.New() + func main() { + nuCPU := runtime.NumCPU() + runtime.GOMAXPROCS(nuCPU) + fmt.Printf("Running with %d CPUs\n", nuCPU) + + gin.SetMode(gin.ReleaseMode) + router := gin.New() router.Use(ratelimit, gin.Recovery(), gin.Logger()) @@ -19,7 +30,7 @@ func main() { //router.DELETE("/room/:roomid", roomDELETE) router.GET("/stream/:roomid", streamRoom) - router.Run(":8080") + router.Run("127.0.0.1:8080") } func index(c *gin.Context) { @@ -29,6 +40,9 @@ func index(c *gin.Context) { func roomGET(c *gin.Context) { roomid := c.ParamValue("roomid") userid := c.FormValue("nick") + if len(userid) > 13 { + userid = userid[0:12] + "..." + } c.HTML(200, "room_login.templ.html", gin.H{ "roomid": roomid, "nick": userid, @@ -42,7 +56,7 @@ func roomPOST(c *gin.Context) { nick := c.FormValue("nick") message := c.PostFormValue("message") - if len(message) > 200 || len(nick) > 20 { + if len(message) > 200 || len(nick) > 13 { c.JSON(400, gin.H{ "status": "failed", "error": "the message or nickname is too long", @@ -54,6 +68,7 @@ func roomPOST(c *gin.Context) { "nick": nick, "message": message, } + messages.Add("inbound", 1) room(roomid).Submit(post) c.JSON(200, post) } @@ -73,6 +88,7 @@ func streamRoom(c *gin.Context) { c.Stream(func(w io.Writer) bool { select { case msg := <-listener: + messages.Add("outbound", 1) c.SSEvent("message", msg) case <-ticker.C: c.SSEvent("stats", Stats()) diff --git a/examples/realtime-advanced/resources/room_login.templ.html b/examples/realtime-advanced/resources/room_login.templ.html index 02bc776..ce7b136 100644 --- a/examples/realtime-advanced/resources/room_login.templ.html +++ b/examples/realtime-advanced/resources/room_login.templ.html @@ -19,13 +19,41 @@ + + + +
+Server-sent events (SSE) is a technology where a browser receives automatic updates from a server via HTTP connection.
The chat and the charts data is provided in realtime using the SSE implemention of Gin Framework.