ip.go 914 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package limiter
  2. import (
  3. "golang.org/x/time/rate"
  4. "sync"
  5. "time"
  6. )
  7. var _ IPRateLimiter = (*ipRateLimiter)(nil)
  8. type IPRateLimiter interface {
  9. addIP(ip string) *rate.Limiter
  10. GetLimiter(ip string) *rate.Limiter
  11. }
  12. type ipRateLimiter struct {
  13. ips map[string]*rate.Limiter
  14. mu *sync.RWMutex
  15. limit rate.Limit
  16. burst int
  17. }
  18. func NewIPRateLimiter(limit time.Duration, burst int) IPRateLimiter {
  19. return &ipRateLimiter{
  20. ips: make(map[string]*rate.Limiter),
  21. mu: new(sync.RWMutex),
  22. limit: rate.Every(limit),
  23. burst: burst,
  24. }
  25. }
  26. func (i *ipRateLimiter) addIP(ip string) *rate.Limiter {
  27. i.mu.Lock()
  28. defer i.mu.Unlock()
  29. limiter := rate.NewLimiter(i.limit, i.burst)
  30. i.ips[ip] = limiter
  31. return limiter
  32. }
  33. func (i *ipRateLimiter) GetLimiter(ip string) *rate.Limiter {
  34. i.mu.Lock()
  35. limiter, exists := i.ips[ip]
  36. if !exists {
  37. i.mu.Unlock()
  38. return i.addIP(ip)
  39. }
  40. i.mu.Unlock()
  41. return limiter
  42. }