diff --git a/defaults.go b/defaults.go index d69fa00..30a18bd 100644 --- a/defaults.go +++ b/defaults.go @@ -4,6 +4,9 @@ const ( // DefaultLimit is the default number of items per page. DefaultLimit = 20 + // DefaultMaxLimit is the default maximum limit that can be set. + DefaultMaxLimit = 20 + // DefaultLimitKeyName is the request key name. DefaultLimitKeyName = "limit" diff --git a/paginator.go b/paginator.go index 716cd6a..2b7a051 100644 --- a/paginator.go +++ b/paginator.go @@ -16,6 +16,9 @@ type Options struct { // DefaultLimit is the default number of items per page. DefaultLimit int64 + // MaxLimit is the maximum limit that can be set. + MaxLimit int64 + // LimitKeyName is the query string key name for the limit. LimitKeyName string @@ -27,6 +30,7 @@ type Options struct { func NewOptions() *Options { return &Options{ DefaultLimit: int64(DefaultLimit), + MaxLimit: int64(DefaultMaxLimit), LimitKeyName: DefaultLimitKeyName, OffsetKeyName: DefaultOffsetKeyName, } diff --git a/utils.go b/utils.go index 0335ef3..c616770 100644 --- a/utils.go +++ b/utils.go @@ -32,6 +32,10 @@ func GetLimitFromRequest(request *http.Request, options *Options) int64 { limit, err = strconv.ParseInt(requestLimit, 10, 64) if err != nil { limit = options.DefaultLimit + + } + if limit > options.MaxLimit { + limit = options.MaxLimit } } else { limit = options.DefaultLimit diff --git a/utils_test.go b/utils_test.go index 486b59d..6c549d1 100644 --- a/utils_test.go +++ b/utils_test.go @@ -23,6 +23,7 @@ func TestGetLimitFromRequest(t *testing.T) { a := assert.New(t) options := NewOptions() + options.MaxLimit = 100 // We define a default limit... options.DefaultLimit = 40 @@ -46,6 +47,12 @@ func TestGetLimitFromRequest(t *testing.T) { options.LimitKeyName = "perpage" request, _ = http.NewRequest("GET", "http://example.com/?perpage=56", nil) a.Equal(int64(56), GetLimitFromRequest(request, options)) + + // We restrict with a max limit + options.MaxLimit = 15 + options.LimitKeyName = "limit" + request, _ = http.NewRequest("GET", "http://example.com/?limit=100", nil) + a.Equal(int64(15), GetLimitFromRequest(request, options)) } func TestGetOffsetFromRequest(t *testing.T) {