36 lines
555 B
Go
36 lines
555 B
Go
package tcp
|
|
|
|
import "time"
|
|
|
|
type limiter struct {
|
|
burst float64
|
|
tokens float64
|
|
last time.Time
|
|
}
|
|
|
|
func newLimiter(perSec int) *limiter {
|
|
if perSec < 1 {
|
|
perSec = 20
|
|
}
|
|
now := time.Now()
|
|
return &limiter{burst: float64(perSec), tokens: float64(perSec), last: now}
|
|
}
|
|
|
|
func (l *limiter) Allow() bool {
|
|
if l == nil {
|
|
return true
|
|
}
|
|
now := time.Now()
|
|
elapsed := now.Sub(l.last).Seconds()
|
|
l.tokens += elapsed * l.burst
|
|
if l.tokens > l.burst {
|
|
l.tokens = l.burst
|
|
}
|
|
l.last = now
|
|
if l.tokens < 1 {
|
|
return false
|
|
}
|
|
l.tokens--
|
|
return true
|
|
}
|