소스 검색

Adds rate limiting

Manu Mtz-Almeida 10 년 전
부모
커밋
3f48e0d45c
3개의 변경된 파일15개의 추가작업 그리고 1개의 파일을 삭제
  1. 2 1
      examples/realtime-advanced/main.go
  2. 12 0
      examples/realtime-advanced/routes.go
  3. 1 0
      examples/realtime-advanced/stats.go

+ 2 - 1
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)

+ 12 - 0
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")
 }

+ 1 - 0
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