Skip to content

Commit

Permalink
Added last seen stats for visitor
Browse files Browse the repository at this point in the history
  • Loading branch information
iambenkay committed Dec 17, 2020
1 parent 02efca7 commit c6e7fc6
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions middleware/rate_limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"golang.org/x/time/rate"
"net/http"
"sync"
"time"
)

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

// RateLimiterMemoryStore is the built-in store implementation for RateLimiter
type RateLimiterMemoryStore struct {
visitors map[string]*rate.Limiter
mutex sync.Mutex
rate rate.Limit
burst int
}
type (
RateLimiterMemoryStore struct {
visitors map[string]visitor
mutex sync.Mutex
rate rate.Limit
burst int
}
visitor struct {
*rate.Limiter
lastSeen time.Time
}
)

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

if store.visitors == nil {
store.visitors = make(map[string]*rate.Limiter)
store.visitors = make(map[string]visitor)
}

limiter, exists := store.visitors[identifier]
if !exists {
limiter = rate.NewLimiter(store.rate, store.burst)
limiter.Limiter = rate.NewLimiter(store.rate, store.burst)
limiter.lastSeen = time.Now()
store.visitors[identifier] = limiter
}

limiter.lastSeen = time.Now()
store.mutex.Unlock()
return limiter.Allow()
}

0 comments on commit c6e7fc6

Please sign in to comment.