pagination.go 696 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package middleware
  2. import (
  3. "fmt"
  4. "strconv"
  5. "github.com/gin-gonic/gin"
  6. )
  7. const (
  8. Page = "page"
  9. PageSize = "page_size"
  10. PageOffset = "page_offset"
  11. )
  12. // Pagination sets page, pageSize and pageOffset to *gin.Context
  13. func Pagination() gin.HandlerFunc {
  14. return func(c *gin.Context) {
  15. page := getSetItem(c, Page, 1)
  16. size := getSetItem(c, PageSize, 20)
  17. c.Set(PageOffset, (page-1)*size)
  18. c.Next()
  19. }
  20. }
  21. func getSetItem(c *gin.Context, k string, d int) int {
  22. var n int
  23. if v := c.Query(k); v != "" {
  24. if i, err := strconv.Atoi(v); err == nil {
  25. if i > 0 {
  26. n = i
  27. }
  28. }
  29. }
  30. if n == 0 {
  31. n = d
  32. }
  33. c.Set(k, n)
  34. c.Request.Header.Set(k, fmt.Sprintf("%d", n))
  35. return n
  36. }