-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: gin util: get page and per from query string.
- Loading branch information
Xavier Zhao
committed
Jun 10, 2020
1 parent
915152e
commit d1a839a
Showing
1 changed file
with
33 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |