12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- package middleware
- import (
- "fmt"
- "strconv"
- "github.com/gin-gonic/gin"
- )
- const (
- Page = "page"
- PageSize = "page_size"
- PageOffset = "page_offset"
- PastureId = "pasture_id"
- )
- // Pagination sets page, pageSize and pageOffset to *gin.Context
- func Pagination() gin.HandlerFunc {
- return func(c *gin.Context) {
- page := getSetItem(c, Page, 1)
- size := getSetItem(c, PageSize, 20)
- c.Set(PageOffset, (page-1)*size)
- c.Next()
- }
- }
- func getSetItem(c *gin.Context, k string, d int) int {
- var n int
- if v := c.Query(k); v != "" {
- if i, err := strconv.Atoi(v); err == nil {
- if i > 0 {
- n = i
- }
- }
- }
- if n == 0 {
- n = d
- }
- c.Set(k, n)
- c.Request.Header.Set(k, fmt.Sprintf("%d", n))
- pastureId, _ := strconv.Atoi(c.Request.Header.Get(PastureId))
- c.Set(PastureId, pastureId)
- return n
- }
|