-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
67 lines (56 loc) · 1.1 KB
/
main.go
File metadata and controls
67 lines (56 loc) · 1.1 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package main
import (
"fmt"
"sync"
"time"
)
type TokenBucket struct {
capacity int
tokens int
fillRate int
mutex sync.Mutex
lastRefill time.Time
}
func NewTokenBucket(capacity, fillRate int) *TokenBucket {
return &TokenBucket{
capacity: capacity,
tokens: capacity,
fillRate: fillRate,
lastRefill: time.Now(),
}
}
func (tb *TokenBucket) refillTokens() {
now := time.Now()
elapsed := now.Sub(tb.lastRefill)
tb.lastRefill = now
tokensToAdd := int(elapsed.Seconds()) * tb.fillRate
tb.tokens = min(tb.capacity, tb.tokens+tokensToAdd)
}
func (tb *TokenBucket) AllowRequest() bool {
tb.mutex.Lock()
defer tb.mutex.Unlock()
tb.refillTokens()
if tb.tokens > 0 {
tb.tokens--
return true
}
return false
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func main() {
tb := NewTokenBucket(5, 1) // Capacity 5 tokens, 1 token per second
// Simulate 10 requests
for i := 0; i < 10; i++ {
if tb.AllowRequest() {
fmt.Println("Request allowed!")
} else {
fmt.Println("Request denied. No tokens available.")
}
time.Sleep(1 * time.Second)
}
}