From 9386d78673bfd0a9cb654f72e10203b229898429 Mon Sep 17 00:00:00 2001 From: Manu Mtz-Almeida Date: Wed, 13 May 2015 03:45:17 +0200 Subject: [PATCH] Better rate limiting --- examples/realtime-advanced/limit.go | 13 ++++++++++--- examples/realtime-advanced/main.go | 2 +- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/examples/realtime-advanced/limit.go b/examples/realtime-advanced/limit.go index da4914c4..5d9ec3be 100644 --- a/examples/realtime-advanced/limit.go +++ b/examples/realtime-advanced/limit.go @@ -1,6 +1,10 @@ package main -import "github.com/gin-gonic/gin" +import ( + "log" + + "github.com/gin-gonic/gin" +) import "github.com/manucorporat/stats" @@ -8,8 +12,11 @@ var ips = stats.New() func ratelimit(c *gin.Context) { ip := c.ClientIP() - value := ips.Add(ip, 1) - if value > 400 { + value := uint64(ips.Add(ip, 1)) + if value >= 400 { + if value%400 == 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 205f9580..729f0e81 100644 --- a/examples/realtime-advanced/main.go +++ b/examples/realtime-advanced/main.go @@ -9,7 +9,7 @@ import ( func main() { router := gin.New() - router.Use(gin.Logger(), ratelimit) + router.Use(ratelimit, gin.Recovery(), gin.Logger()) router.LoadHTMLGlob("resources/*.templ.html") router.Static("/static", "resources/static")