Skip to content

Commit

Permalink
add: gin util: get page and per from query string.
Browse files Browse the repository at this point in the history
  • Loading branch information
Xavier Zhao committed Jun 10, 2020
1 parent 915152e commit d1a839a
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions http/gin/page.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package gin

import (
"github.com/gin-gonic/gin"
"strconv"
)

// GetPagePerFromQs retrieves the page number and the number of items per page from query string in request.
// The prerequisite for using this function is that the parameters' name of the page number and the number of items
// per page in query string must be `page` and `per`, like `example.com?page=2&per=10`.
//
// If the page parameter in query string is not a number, the returned page will be 1. And if the per parameter
// in query string is not a number, the returned per will be defaultPer, if the requested per is larger than
// maxPer, the returned per will be maxPer.
func GetPagePerFromQs(c *gin.Context, defaultPer, maxPer int) (page, per int) {
pageStr := c.Query("page")
perStr := c.Query("per")

page, err := strconv.Atoi(pageStr)
if err != nil {
page = 1
}

per, err = strconv.Atoi(perStr)
if err != nil {
per = defaultPer
}
if per > maxPer {
per = maxPer
}

return
}

0 comments on commit d1a839a

Please sign in to comment.