bustle/cmd/bustled/throttler.go

43 lines
766 B
Go

package main
import "time"
type Throttler interface {
Touch(string)
Throttled(string) bool
SetInterval(time.Duration)
Now() time.Time
}
type MapThrottler struct {
interval time.Duration
users map[string]time.Time
}
func NewThrottler(interval time.Duration) Throttler {
return &MapThrottler{
interval: interval,
users: map[string]time.Time{},
}
}
func (t *MapThrottler) SetInterval(interval time.Duration) {
t.interval = interval
}
func (t *MapThrottler) Touch(username string) {
t.users[username] = t.Now()
}
func (t *MapThrottler) Now() time.Time {
return time.Now()
}
func (t *MapThrottler) Throttled(username string) bool {
lastTouch, ok := t.users[username]
if !ok {
return false
}
return t.Now().Sub(lastTouch) < t.interval
}