Created
August 9, 2019 09:08
-
-
Save plutov/147290e88e4cd10c2850e542df4b5031 to your computer and use it in GitHub Desktop.
rate.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"sync" | |
"golang.org/x/time/rate" | |
) | |
// IPRateLimiter . | |
type IPRateLimiter struct { | |
ips map[string]*rate.Limiter | |
mu *sync.RWMutex | |
r rate.Limit | |
b int | |
} | |
// NewIPRateLimiter . | |
func NewIPRateLimiter(r rate.Limit, b int) *IPRateLimiter { | |
i := &IPRateLimiter{ | |
ips: make(map[string]*rate.Limiter), | |
mu: &sync.RWMutex{}, | |
r: r, | |
b: b, | |
} | |
return i | |
} | |
// AddIP creates a new rate limiter and adds it to the ips map, | |
// using the IP address as the key | |
func (i *IPRateLimiter) AddIP(ip string) *rate.Limiter { | |
i.mu.Lock() | |
defer i.mu.Unlock() | |
limiter := rate.NewLimiter(i.r, i.b) | |
i.ips[ip] = limiter | |
return limiter | |
} | |
// GetLimiter returns the rate limiter for the provided IP address if it exists. | |
// Otherwise calls AddIP to add IP address to the map | |
func (i *IPRateLimiter) GetLimiter(ip string) *rate.Limiter { | |
i.mu.Lock() | |
limiter, exists := i.ips[ip] | |
if !exists { | |
i.mu.Unlock() | |
return i.AddIP(ip) | |
} | |
i.mu.Unlock() | |
return limiter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment