pcm-kubernetes/app/page.go

62 lines
1.1 KiB
Go

package app
type Page[T any] struct {
// 当前页码
PageNum int64 `json:"pageNum"`
//每页显示条数
PageSize int64 `json:"pageSize"`
// 总数量
Total int64 `json:"total"`
// 总页数
TotalPage int64 `json:"totalPage"`
// 数据列表
List []T `json:"list"`
}
// Paginator 生成新的分页数据对象
func Paginator[T any](items *Page[T], total, pageNum, pageSize int64) *Page[T] {
var (
pageStart int64
pageEnd int64
)
if pageNum <= 0 {
pageNum = 1
}
if pageSize <= 0 {
pageSize = 10
}
//总页数
totalPages := total / pageSize
if (total % pageSize) > 0 {
totalPages += 1
}
if pageNum*pageSize < total {
pageEnd = pageNum * pageSize
pageStart = pageEnd - pageSize
} else {
pageEnd = total
pageStart = pageSize * (totalPages - 1)
}
if pageEnd > total {
pageEnd = total
}
if total <= 0 {
items.List = make([]T, 0)
} else {
items.List = items.List[pageStart:pageEnd]
}
return &Page[T]{
PageNum: pageNum,
PageSize: pageSize,
TotalPage: totalPages,
Total: total,
List: items.List,
}
}