page.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package common
  2. type PageParams struct {
  3. Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page"`
  4. PageSize int64 `protobuf:"varint,2,opt,name=pageSize,proto3" json:"pageSize"`
  5. Total int64 `protobuf:"varint,3,opt,name=total,proto3" json:"total"`
  6. Last bool `protobuf:"varint,4,opt,name=last,proto3" json:"last"`
  7. }
  8. // GetPageParams 从0开始的分页计算(返回limit和offset)
  9. func (p *PageParams) GetPageParams() (limit int, offset int) {
  10. // 1. 校正无效参数
  11. if p.Page < 0 {
  12. p.Page = 0 // 页码为负时重置为第0页
  13. }
  14. if p.PageSize <= 0 {
  15. p.PageSize = 10 // 页大小无效时用默认值
  16. }
  17. // 2. 处理总数据为0的情况
  18. if p.Total <= 0 {
  19. p.Last = true
  20. return 0, 0
  21. }
  22. // 3. 计算基础偏移量和最大可显示的页码
  23. offset64 := p.Page * p.PageSize
  24. maxPage := (p.Total - 1) / p.PageSize // 最后一页的页码(从0开始)
  25. // 4. 如果当前页超出最大页码,强制跳转到最后一页
  26. if p.Page > maxPage {
  27. p.Page = maxPage
  28. offset64 = p.Page * p.PageSize
  29. }
  30. // 5. 计算实际返回的条数(最后一页可能不足一页)
  31. remaining := p.Total - offset64
  32. if remaining < p.PageSize {
  33. limit = int(remaining)
  34. p.Last = true // 剩余数据不足一页,说明是最后一页
  35. } else {
  36. limit = int(p.PageSize)
  37. p.Last = p.Page == maxPage // 当前页等于最大页时才是最后一页
  38. }
  39. return limit, int(offset64)
  40. }