Skip to content

Instantly share code, notes, and snippets.

@hxzhouh
Created September 24, 2024 11:01
Show Gist options
  • Save hxzhouh/51020e18622c2e38ebf21cd6a9dc5cc6 to your computer and use it in GitHub Desktop.
Save hxzhouh/51020e18622c2e38ebf21cd6a9dc5cc6 to your computer and use it in GitHub Desktop.
type FixedWindowCounter struct {
mu sync.Mutex
count int
limit int
duration time.Duration
}
func NewFixedWindowCounter(limit int, duration time.Duration) *FixedWindowCounter {
l := &FixedWindowCounter{
limit: limit,
duration: duration, // Setting the duration of the time window。
}
go l.resetLimit()
return l
}
func (f *FixedWindowCounter) resetLimit() {
ticker := time.NewTicker(f.duration)
for {
select {
case <-ticker.C:
f.mu.Lock()
f.count = 0
f.mu.Unlock()
}
}
}
func (f *FixedWindowCounter) Allow() bool {
f.mu.Lock()
defer f.mu.Unlock()
// allowed request
if f.count < f.limit {
f.count++
return true
}
// reject request
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment