| 1 |
package g8 |
| 2 |
|
| 3 |
import ( |
| 4 |
"sync" |
| 5 |
"time" |
| 6 |
) |
| 7 |
|
| 8 |
|
| 9 |
type RateLimiter struct { |
| 10 |
maximumExecutionsPerSecond int |
| 11 |
executionsLeftInWindow int |
| 12 |
windowStartTime time.Time |
| 13 |
mutex sync.Mutex |
| 14 |
} |
| 15 |
|
| 16 |
|
| 17 |
func NewRateLimiter(maximumExecutionsPerSecond int) *RateLimiter { |
| 18 |
return &RateLimiter{ |
| 19 |
windowStartTime: time.Now(), |
| 20 |
executionsLeftInWindow: maximumExecutionsPerSecond, |
| 21 |
maximumExecutionsPerSecond: maximumExecutionsPerSecond, |
| 22 |
} |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
func (r *RateLimiter) Try() bool { |
| 31 |
r.mutex.Lock() |
| 32 |
defer r.mutex.Unlock() |
| 33 |
if time.Now().Add(-time.Second).After(r.windowStartTime) { |
| 34 |
r.windowStartTime = time.Now() |
| 35 |
r.executionsLeftInWindow = r.maximumExecutionsPerSecond |
| 36 |
} |
| 37 |
if r.executionsLeftInWindow == 0 { |
| 38 |
return false |
| 39 |
} |
| 40 |
r.executionsLeftInWindow-- |
| 41 |
return true |
| 42 |
} |