Files
kotosoft-id/kotosoft-id-backend/internal/middleware/ratelimiter.go
T
2026-03-09 18:09:02 +03:00

60 lines
1.1 KiB
Go

package middleware
import (
"net/http"
"github.com/dusiburg/kotosoft-id/internal/models"
"github.com/dusiburg/kotosoft-id/internal/services"
"github.com/gin-gonic/gin"
)
func RateLimit(
limiter *services.RateLimiter,
cfg services.RateLimitConfig,
keyFn func(c *gin.Context) string,
) gin.HandlerFunc {
return func(c *gin.Context) {
key := keyFn(c)
allowed, remaining, _ := limiter.Allow(c.Request.Context(), key, cfg)
c.Header("X-RateLimit-Limit", itoa(cfg.Max))
c.Header("X-RateLimit-Remaining", itoa(remaining))
if !allowed {
c.JSON(http.StatusTooManyRequests, models.ErrTooManyRequests)
c.Abort()
return
}
c.Next()
}
}
func LoginKeyFn(c *gin.Context) string {
return "login:" + c.ClientIP()
}
func IPKeyFn(prefix string) func(c *gin.Context) string {
return func(c *gin.Context) string {
return prefix + ":" + c.ClientIP()
}
}
func itoa(n int) string {
if n < 0 {
return "0"
}
buf := make([]byte, 0, 10)
if n == 0 {
return "0"
}
for n > 0 {
buf = append([]byte{byte('0' + n%10)}, buf...)
n /= 10
}
return string(buf)
}