Skip to content

Commit e0e9688

Browse files
committed
removed redundant mutex declaration
1 parent dc04e2c commit e0e9688

File tree

2 files changed

+5
-9
lines changed

2 files changed

+5
-9
lines changed

middleware/rate_limiter.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ type (
2121
// SourceFunc uses echo.Context to extract the identifier for a visitor
2222
SourceFunc func(context echo.Context) string
2323
// Store defines a store for the rate limiter
24-
Store TokenStore
24+
Store TokenStore
2525
}
2626
)
2727

@@ -83,6 +83,10 @@ func (store *InMemoryStore) ShouldAllow(identifier string) bool {
8383
store.mutex.Lock()
8484
defer store.mutex.Unlock()
8585

86+
if store.visitors == nil {
87+
store.visitors = make(map[string]*rate.Limiter)
88+
}
89+
8690
limiter, exists := store.visitors[identifier]
8791
if !exists {
8892
limiter = rate.NewLimiter(store.rate, store.burst)

middleware/rate_limiter_test.go

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,14 @@ package middleware
33
import (
44
"github.com/labstack/echo/v4"
55
"github.com/stretchr/testify/assert"
6-
"golang.org/x/time/rate"
76
"net/http"
87
"net/http/httptest"
9-
"sync"
108
"testing"
119
"time"
1210
)
1311

1412
func TestRateLimiter(t *testing.T) {
1513
var inMemoryStore = new(InMemoryStore)
16-
inMemoryStore.visitors = map[string]*rate.Limiter{}
17-
inMemoryStore.mutex = sync.Mutex{}
1814
inMemoryStore.rate = 1
1915
inMemoryStore.burst = 3
2016

@@ -57,8 +53,6 @@ func TestRateLimiter(t *testing.T) {
5753

5854
func TestRateLimiterWithConfig(t *testing.T) {
5955
var inMemoryStore = new(InMemoryStore)
60-
inMemoryStore.visitors = map[string]*rate.Limiter{}
61-
inMemoryStore.mutex = sync.Mutex{}
6256
inMemoryStore.rate = 1
6357
inMemoryStore.burst = 3
6458

@@ -104,8 +98,6 @@ func TestRateLimiterWithConfig(t *testing.T) {
10498

10599
func TestInMemoryStore_ShouldAllow(t *testing.T) {
106100
var inMemoryStore = new(InMemoryStore)
107-
inMemoryStore.visitors = map[string]*rate.Limiter{}
108-
inMemoryStore.mutex = sync.Mutex{}
109101
inMemoryStore.rate = 1
110102
inMemoryStore.burst = 3
111103

0 commit comments

Comments
 (0)