implement rate limiting

This commit is contained in:
2025-03-25 15:12:56 +00:00
parent 107f8e2642
commit 1a531af4f8
4 changed files with 40 additions and 1 deletions

35
helpers/ratelimit.go Normal file
View File

@@ -0,0 +1,35 @@
package helpers
import (
"net"
"net/http"
"sync"
"golang.org/x/time/rate"
)
var visitors = make(map[string]*rate.Limiter)
var mu sync.Mutex
func GetVisitorLimiter(ip string) *rate.Limiter {
mu.Lock()
defer mu.Unlock()
limiter, exists := visitors[ip]
if !exists {
limiter = rate.NewLimiter(1, 5)
visitors[ip] = limiter
}
return limiter
}
func RateLimit(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
if !GetVisitorLimiter(ip).Allow() {
http.Error(w, "Too many requests", http.StatusTooManyRequests)
return
}
next.ServeHTTP(w, r)
})
}