-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlimiter.go
70 lines (58 loc) · 1.57 KB
/
limiter.go
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
68
69
70
package ratelimiter
import (
"context"
"net/http"
"time"
"github.com/rs/zerolog"
rip "github.com/vikram1565/request-ip"
"github.com/mathcale/goexpert-rate-limiter-challenge/internal/pkg/logger"
"github.com/mathcale/goexpert-rate-limiter-challenge/internal/pkg/ratelimiter/strategies"
)
type RateLimiterInterface interface {
Check(ctx context.Context, r *http.Request) (*strategies.RateLimiterResult, error)
}
type RateLimiter struct {
Logger zerolog.Logger
Strategy strategies.LimiterStrategyInterface
MaxRequestsPerIP int
MaxRequestsPerToken int
TimeWindowMillis int
}
func NewRateLimiter(
logger logger.LoggerInterface,
strategy strategies.LimiterStrategyInterface,
ipMaxReqs int,
tokenMaxReqs int,
timeWindow int,
) *RateLimiter {
return &RateLimiter{
Logger: logger.GetLogger(),
Strategy: strategy,
MaxRequestsPerIP: ipMaxReqs,
MaxRequestsPerToken: tokenMaxReqs,
TimeWindowMillis: timeWindow,
}
}
func (rl *RateLimiter) Check(ctx context.Context, r *http.Request) (*strategies.RateLimiterResult, error) {
var key string
var limit int64
duration := time.Duration(rl.TimeWindowMillis) * time.Millisecond
apiKey := r.Header.Get("API_KEY")
if apiKey != "" {
key = apiKey
limit = int64(rl.MaxRequestsPerToken)
} else {
key = rip.GetClientIP(r)
limit = int64(rl.MaxRequestsPerIP)
}
req := &strategies.RateLimiterRequest{
Key: key,
Limit: limit,
Duration: duration,
}
result, err := rl.Strategy.Check(r.Context(), req)
if err != nil {
return nil, err
}
return result, nil
}