You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
1.7 KiB
102 lines
1.7 KiB
package page
|
|
|
|
import (
|
|
"math"
|
|
)
|
|
|
|
// 服务端用
|
|
|
|
const (
|
|
DefaultPage = 1
|
|
MinPageSize = 1
|
|
DefaultPageSize = 10
|
|
MaxPageSize = 1000
|
|
)
|
|
|
|
type Pagination struct {
|
|
Page int32 `json:"page"`
|
|
PageSize int32 `json:"page_size"`
|
|
TotalPage int32 `json:"total_page"`
|
|
Total int32 `json:"total"`
|
|
}
|
|
|
|
type Integer interface {
|
|
~int | ~int32
|
|
}
|
|
|
|
// 用于对一个切片分页
|
|
func PageToSlice[T Integer](page, pageSize, total T) (begin, end T) {
|
|
if page < DefaultPage {
|
|
page = DefaultPage
|
|
}
|
|
|
|
if pageSize <= 0 {
|
|
pageSize = DefaultPageSize
|
|
}
|
|
|
|
if pageSize <= MinPageSize {
|
|
pageSize = MinPageSize
|
|
}
|
|
|
|
if pageSize >= MaxPageSize {
|
|
pageSize = MaxPageSize
|
|
}
|
|
|
|
// 计算总页数
|
|
totalPage := (total / pageSize) + 1
|
|
if page > totalPage {
|
|
page = totalPage
|
|
}
|
|
|
|
begin = (page - 1) * pageSize
|
|
if total-begin <= pageSize {
|
|
end = total
|
|
} else {
|
|
end = begin + pageSize
|
|
}
|
|
return
|
|
}
|
|
|
|
// 用于分页查询
|
|
func PageToOffset[T Integer](page, pageSize T) (offset, limit T) {
|
|
if page < DefaultPage {
|
|
page = DefaultPage
|
|
}
|
|
|
|
if pageSize <= 0 {
|
|
pageSize = DefaultPageSize
|
|
}
|
|
|
|
if pageSize <= MinPageSize {
|
|
pageSize = MinPageSize
|
|
}
|
|
|
|
if pageSize >= MaxPageSize {
|
|
pageSize = MaxPageSize
|
|
}
|
|
|
|
offset = (page - 1) * pageSize
|
|
limit = pageSize
|
|
return
|
|
}
|
|
|
|
func CalcPagination[T Integer, E Integer](page, pageSize T, total E) (res Pagination) {
|
|
if page < DefaultPage {
|
|
page = DefaultPage
|
|
}
|
|
|
|
if pageSize <= MinPageSize {
|
|
pageSize = MinPageSize
|
|
}
|
|
|
|
if pageSize >= MaxPageSize {
|
|
pageSize = MaxPageSize
|
|
}
|
|
res.Page = int32(page)
|
|
res.PageSize = int32(pageSize)
|
|
res.Total = int32(total)
|
|
|
|
res.TotalPage = int32(math.Ceil(float64(res.Total) / float64(res.PageSize)))
|
|
|
|
return
|
|
}
|
|
|