Skip to content

Commit c6e7fc6

Browse files
committed
Added last seen stats for visitor
1 parent 02efca7 commit c6e7fc6

File tree

1 file changed

+17
-9
lines changed

1 file changed

+17
-9
lines changed

middleware/rate_limiter.go

+17-9
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"golang.org/x/time/rate"
66
"net/http"
77
"sync"
8+
"time"
89
)
910

1011
// RateLimiterStore is the interface to be implemented by custom stores.
@@ -73,27 +74,34 @@ func RateLimiterWithConfig(config RateLimiterConfig) echo.MiddlewareFunc {
7374
}
7475

7576
// RateLimiterMemoryStore is the built-in store implementation for RateLimiter
76-
type RateLimiterMemoryStore struct {
77-
visitors map[string]*rate.Limiter
78-
mutex sync.Mutex
79-
rate rate.Limit
80-
burst int
81-
}
77+
type (
78+
RateLimiterMemoryStore struct {
79+
visitors map[string]visitor
80+
mutex sync.Mutex
81+
rate rate.Limit
82+
burst int
83+
}
84+
visitor struct {
85+
*rate.Limiter
86+
lastSeen time.Time
87+
}
88+
)
8289

8390
// Allow implements RateLimiterStore.Allow
8491
func (store *RateLimiterMemoryStore) Allow(identifier string) bool {
8592
store.mutex.Lock()
8693

8794
if store.visitors == nil {
88-
store.visitors = make(map[string]*rate.Limiter)
95+
store.visitors = make(map[string]visitor)
8996
}
9097

9198
limiter, exists := store.visitors[identifier]
9299
if !exists {
93-
limiter = rate.NewLimiter(store.rate, store.burst)
100+
limiter.Limiter = rate.NewLimiter(store.rate, store.burst)
101+
limiter.lastSeen = time.Now()
94102
store.visitors[identifier] = limiter
95103
}
96-
104+
limiter.lastSeen = time.Now()
97105
store.mutex.Unlock()
98106
return limiter.Allow()
99107
}

0 commit comments

Comments
 (0)