Skip to content

Commit

Permalink
feat: support not allow empty for concurrent limiter
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Jun 18, 2020
1 parent 196f56d commit 4e1e4a8
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions middleware/concurrent_limiter.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,11 @@ var (
Message: "submit too frequently",
Category: ErrConcurrentLimiterCategory,
}
ErrNotAllowEmpty = &hes.Error{
StatusCode: http.StatusBadRequest,
Message: "empty value is not allowed",
Category: ErrConcurrentLimiterCategory,
}
ErrRequireLockFunction = errors.New("require lock function")
)

Expand All @@ -61,6 +66,8 @@ type (
// Lock lock function
Lock ConcurrentLimiterLock
Skipper elton.Skipper
// NotAllowEmpty is value is empty, will return error
NotAllowEmpty bool
}
// concurrentLimiterKeyInfo the concurrent key's info
concurrentLimiterKeyInfo struct {
Expand Down Expand Up @@ -142,6 +149,10 @@ func NewConcurrentLimiter(config ConcurrentLimiterConfig) elton.Handler {
} else {
v = gjson.GetBytes(c.RequestBody, name).String()
}
if config.NotAllowEmpty && len(v) == 0 {
err = ErrNotAllowEmpty
return
}
sb.WriteString(v)
if i < keyLength-1 {
sb.WriteRune(',')
Expand Down
16 changes: 16 additions & 0 deletions middleware/concurrent_limiter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,4 +119,20 @@ func TestConcurrentLimiter(t *testing.T) {
err := fn(c)
assert.Equal("message=key is invalid", err.Error())
})

t.Run("not allow empty", func(t *testing.T) {
assert := assert.New(t)
fn := NewConcurrentLimiter(ConcurrentLimiterConfig{
NotAllowEmpty: true,
Keys: []string{
"p:id",
},
Lock: func(key string, c *elton.Context) (success bool, unlock func(), err error) {
return
},
})
c := elton.NewContext(nil, httptest.NewRequest("GET", "/", nil))
err := fn(c)
assert.Equal(ErrNotAllowEmpty, err)
})
}

0 comments on commit 4e1e4a8

Please sign in to comment.