Add rate limitting
This commit is contained in:
		
							
								
								
									
										15
									
								
								examples/realtime-advanced/limit.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										15
									
								
								examples/realtime-advanced/limit.go
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,15 @@
 | 
			
		||||
package main
 | 
			
		||||
 | 
			
		||||
import "github.com/gin-gonic/gin"
 | 
			
		||||
 | 
			
		||||
import "github.com/manucorporat/stats"
 | 
			
		||||
 | 
			
		||||
var ips = stats.New()
 | 
			
		||||
 | 
			
		||||
func ratelimit(c *gin.Context) {
 | 
			
		||||
	ip := c.ClientIP()
 | 
			
		||||
	value := ips.Add(ip, 1)
 | 
			
		||||
	if value > 1000 {
 | 
			
		||||
		c.AbortWithStatus(401)
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
@ -8,7 +8,9 @@ import (
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func main() {
 | 
			
		||||
	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)
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user