ip.go 789 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  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 sync.Map
  14. limit rate.Limit
  15. burst int
  16. }
  17. func NewIPRateLimiter(limit time.Duration, burst int) IPRateLimiter {
  18. return &ipRateLimiter{
  19. ips: sync.Map{},
  20. limit: rate.Every(limit),
  21. burst: burst,
  22. }
  23. }
  24. func (i *ipRateLimiter) addIP(ip string) *rate.Limiter {
  25. store, _ := i.ips.LoadOrStore(ip, rate.NewLimiter(i.limit, i.burst))
  26. return store.(*rate.Limiter)
  27. }
  28. func (i *ipRateLimiter) GetLimiter(ip string) *rate.Limiter {
  29. limiter, exists := i.ips.Load(ip)
  30. if !exists {
  31. return i.addIP(ip)
  32. }
  33. return limiter.(*rate.Limiter)
  34. }