From 3f48e0d45c49a6de036974038edb4547492f30c0 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Thu, 14 May 2015 20:25:55 +0200 Subject: [PATCH] Adds rate limiting --- examples/realtime-advanced/main.go | 3 ++- examples/realtime-advanced/routes.go | 12 ++++++++++++ examples/realtime-advanced/stats.go | 1 + 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/examples/realtime-advanced/main.go b/examples/realtime-advanced/main.go index d209d28c..6aa781ed 100644 --- a/examples/realtime-advanced/main.go +++ b/examples/realtime-advanced/main.go @@ -26,7 +26,8 @@ func StartWorkers() { func StartGin() { gin.SetMode(gin.ReleaseMode) - router := gin.Default() + router := gin.New() + router.Use(rateLimit, gin.Recovery(), gin.Logger()) router.LoadHTMLGlob("resources/*.templ.html") router.Static("/static", "resources/static") router.GET("/", index) diff --git a/examples/realtime-advanced/routes.go b/examples/realtime-advanced/routes.go index fb1f5b6e..8a7ac646 100644 --- a/examples/realtime-advanced/routes.go +++ b/examples/realtime-advanced/routes.go @@ -3,12 +3,24 @@ package main import ( "html" "io" + "log" "strings" "time" "github.com/gin-gonic/gin" ) +func rateLimit(c *gin.Context) { + ip := c.ClientIP() + value := ips.Add(ip, 1) + if value > 800 { + if int(value)%700 == 0 { + log.Printf("ip block: %s, count: %f\n", ip, value) + } + c.AbortWithStatus(503) + } +} + func index(c *gin.Context) { c.Redirect(301, "/room/hn") } diff --git a/examples/realtime-advanced/stats.go b/examples/realtime-advanced/stats.go index 896787f9..32c52835 100644 --- a/examples/realtime-advanced/stats.go +++ b/examples/realtime-advanced/stats.go @@ -8,6 +8,7 @@ import ( "github.com/manucorporat/stats" ) +var ips = stats.New() var messages = stats.New() var users = stats.New() var mutexStats sync.RWMutex