pagination.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. // Copyright 2019 autocareai.com. All rights reserved.
  2. // Use of this source code is governed by autocareai.com.
  3. package model
  4. import (
  5. "strings"
  6. "time"
  7. )
  8. // 游标分页
  9. type CursorPagination struct {
  10. Top string
  11. TopNum string
  12. TopExtra string
  13. Bottom string
  14. BottomNum string
  15. BottomExtra string
  16. }
  17. func NewCursorPagination() *CursorPagination {
  18. return &CursorPagination{}
  19. }
  20. // 分割分页的top/bottom
  21. func (c *CursorPagination) SplitTopBottomData(topParam, bottomParam string) {
  22. if topParam == "" {
  23. c.Top = "0"
  24. c.TopNum = "0"
  25. c.TopExtra = "0"
  26. } else {
  27. top := strings.Split(topParam, ",")
  28. c.Top = top[0]
  29. c.TopNum = top[1]
  30. c.TopExtra = top[2]
  31. }
  32. if bottomParam == "" {
  33. c.Bottom = "0"
  34. c.BottomNum = "0"
  35. c.BottomExtra = "0"
  36. } else {
  37. bottom := strings.Split(bottomParam, ",")
  38. c.Bottom = bottom[0]
  39. c.BottomNum = bottom[1]
  40. c.BottomExtra = bottom[2]
  41. }
  42. }
  43. // 传统分页
  44. type Pagination struct {
  45. CurrentPage int `json:"current_page"` // 当前页
  46. PerPage int `json:"per_page"` // 每一页多少条
  47. Total int `json:"total"` // 总条数
  48. FirstPage int `json:"first_page"` // 第一页
  49. LastPage int `json:"last_page"` // 最后页
  50. PrevPage int `json:"prev_page"` // 上一页
  51. NextPage int `json:"next_page"` // 下一页
  52. Limit int `json:"limit"`
  53. Offset int `json:"offset"`
  54. RequestTime int64 `json:"request_time"`
  55. }
  56. func NewPagination(currentPage, perPage int, requestTime int64) *Pagination {
  57. if currentPage == 0 {
  58. currentPage = 1
  59. }
  60. if requestTime == 0 {
  61. requestTime = time.Now().Unix()
  62. }
  63. return &Pagination{
  64. CurrentPage: currentPage,
  65. PerPage: perPage,
  66. PrevPage: -1,
  67. NextPage: -1,
  68. RequestTime: requestTime,
  69. }
  70. }
  71. // 根据当前页获取分页条数和偏移量
  72. func (p *Pagination) GetLimitOffset() *Pagination {
  73. var num int
  74. if p.CurrentPage < 1 {
  75. num = 0
  76. } else {
  77. num = p.CurrentPage - 1
  78. }
  79. p.Limit = p.PerPage
  80. p.Offset = num * p.PerPage
  81. return p
  82. }
  83. // 计算上、下、首、末页
  84. func (p *Pagination) CalPage(total int) {
  85. p.Total = total
  86. // 第一页
  87. if total != 0 {
  88. p.FirstPage = 1
  89. }
  90. // 最后页
  91. p.LastPage = total / p.PerPage
  92. if total%p.PerPage != 0 {
  93. p.LastPage += 1
  94. }
  95. // 上一页
  96. if p.CurrentPage > 1 {
  97. p.PrevPage = p.CurrentPage - 1
  98. }
  99. // 下一页
  100. if total > p.PerPage*p.CurrentPage {
  101. p.NextPage = p.CurrentPage + 1
  102. }
  103. }