monitor/pkg/limiter.go

41 lines
646 B
Go
Raw Permalink Normal View History

2019-11-22 10:11:26 +00:00
package pkg
import (
"sync"
"time"
)
type LimiterServer struct {
2019-11-25 06:12:08 +00:00
interval time.Duration
maxCount int
sync.Mutex
2019-11-26 05:50:08 +00:00
reqCount int
time time.Time
2019-11-22 10:11:26 +00:00
}
2019-11-26 05:50:08 +00:00
func NewLimiterServer(interval time.Duration, maxCount int) *LimiterServer {
2019-11-25 06:12:08 +00:00
return &LimiterServer{
2019-11-26 05:50:08 +00:00
interval: interval,
maxCount: maxCount,
2019-11-22 10:11:26 +00:00
}
2019-11-25 06:12:08 +00:00
}
2019-11-22 10:11:26 +00:00
2019-11-25 06:12:08 +00:00
func (limiter *LimiterServer) IsAvailable() bool {
limiter.Lock()
defer limiter.Unlock()
2019-11-26 05:50:08 +00:00
now := time.Now()
2019-11-22 10:11:26 +00:00
2019-11-26 05:50:08 +00:00
if limiter.time.IsZero() ||
limiter.time.Add(limiter.interval).Before(now) {
limiter.reqCount = 0
2019-11-25 06:12:08 +00:00
}
2019-11-22 10:11:26 +00:00
2019-11-25 06:12:08 +00:00
if limiter.reqCount < limiter.maxCount {
limiter.reqCount += 1
2019-11-26 05:50:08 +00:00
limiter.time = now
2019-11-25 06:12:08 +00:00
return true
}
2019-11-22 10:11:26 +00:00
2019-11-25 06:12:08 +00:00
return false
2019-11-22 10:11:26 +00:00
}