gitstack

demo/acme-pay code browser

508 B Go 28 lines 2024-01-20 · ae7067d raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package middleware

import "time"

// Limiter is a tiny token-bucket rate limiter.
type Limiter struct {
	tokens   int
	max      int
	refill   time.Duration
	lastSeen time.Time
}

func New(max int, refill time.Duration) *Limiter {
	return &Limiter{tokens: max, max: max, refill: refill, lastSeen: time.Now()}
}

func (l *Limiter) Allow() bool {
	now := time.Now()
	if now.Sub(l.lastSeen) >= l.refill {
		l.tokens = l.max
		l.lastSeen = now
	}
	if l.tokens <= 0 {
		return false
	}
	l.tokens--
	return true
}