monitor/pkg/limiter.go

43 lines
646 B
Go
Raw 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
reqCount int
startTime time.Time
2019-11-22 10:11:26 +00:00
}
2019-11-25 06:12:08 +00:00
func NewLimiterServer(i time.Duration, c int) *LimiterServer {
return &LimiterServer{
interval: i,
maxCount: c,
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-22 10:11:26 +00:00
2019-11-25 06:12:08 +00:00
if limiter.startTime.IsZero() ||
limiter.startTime.Add(limiter.interval).Before(time.Now()) {
limiter.reqCount = 1
limiter.startTime = time.Now()
2019-11-22 10:11:26 +00:00
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
if limiter.reqCount < limiter.maxCount {
limiter.reqCount += 1
2019-11-22 10:11:26 +00:00
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
}