...

Source file src/github.com/ory/x/pagination/parse.go

Documentation: github.com/ory/x/pagination

     1  /*
     2   * Copyright © 2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   * @author		Aeneas Rekkas <aeneas+oss@aeneas.io>
    17   * @copyright 	2017-2018 Aeneas Rekkas <aeneas+oss@aeneas.io>
    18   * @license 	Apache-2.0
    19   */
    20  
    21  package pagination
    22  
    23  import (
    24  	"net/http"
    25  	"strconv"
    26  )
    27  
    28  // Parse parses limit and offset from *http.Request with given limits and defaults.
    29  func Parse(r *http.Request, defaultLimit, defaultOffset, maxLimit int) (int, int) {
    30  	var offset, limit int
    31  
    32  	if offsetParam := r.URL.Query().Get("offset"); offsetParam == "" {
    33  		offset = defaultOffset
    34  	} else {
    35  		if offset64, err := strconv.ParseInt(offsetParam, 10, 64); err != nil {
    36  			offset = defaultOffset
    37  		} else {
    38  			offset = int(offset64)
    39  		}
    40  	}
    41  
    42  	if limitParam := r.URL.Query().Get("limit"); limitParam == "" {
    43  		limit = defaultLimit
    44  	} else {
    45  		if limit64, err := strconv.ParseInt(limitParam, 10, 64); err != nil {
    46  			limit = defaultLimit
    47  		} else {
    48  			limit = int(limit64)
    49  		}
    50  	}
    51  
    52  	if limit > maxLimit {
    53  		limit = maxLimit
    54  	}
    55  
    56  	if limit < 0 {
    57  		limit = 0
    58  	}
    59  
    60  	if offset < 0 {
    61  		offset = 0
    62  	}
    63  
    64  	return limit, offset
    65  }
    66  

View as plain text