| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- package common
- type PageParams struct {
- Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page"`
- PageSize int64 `protobuf:"varint,2,opt,name=pageSize,proto3" json:"pageSize"`
- Total int64 `protobuf:"varint,3,opt,name=total,proto3" json:"total"`
- Last bool `protobuf:"varint,4,opt,name=last,proto3" json:"last"`
- }
- // GetPageParams 从0开始的分页计算(返回limit和offset)
- func (p *PageParams) GetPageParams() (limit int, offset int) {
- // 1. 校正无效参数
- if p.Page < 0 {
- p.Page = 0 // 页码为负时重置为第0页
- }
- if p.PageSize <= 0 {
- p.PageSize = 10 // 页大小无效时用默认值
- }
- // 2. 处理总数据为0的情况
- if p.Total <= 0 {
- p.Last = true
- return 0, 0
- }
- // 3. 计算基础偏移量和最大可显示的页码
- offset64 := p.Page * p.PageSize
- maxPage := (p.Total - 1) / p.PageSize // 最后一页的页码(从0开始)
- // 4. 如果当前页超出最大页码,强制跳转到最后一页
- if p.Page > maxPage {
- p.Page = maxPage
- offset64 = p.Page * p.PageSize
- }
- // 5. 计算实际返回的条数(最后一页可能不足一页)
- remaining := p.Total - offset64
- if remaining < p.PageSize {
- limit = int(remaining)
- p.Last = true // 剩余数据不足一页,说明是最后一页
- } else {
- limit = int(p.PageSize)
- p.Last = p.Page == maxPage // 当前页等于最大页时才是最后一页
- }
- return limit, int(offset64)
- }
|