通用包
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.
utils/pagination/v1/pagination.go

94 lines
1.5 KiB

2 years ago
package page
2 years ago
2 years ago
import (
"math"
)
2 years ago
2 years ago
// 服务端用
2 years ago
const (
DefaultPage = 1
MinPageSize = 10
2 years ago
MaxPageSize = 1000
2 years ago
)
2 years ago
type Pagination struct {
Page int32 `json:"page"`
PageSize int32 `json:"page_size"`
TotalPage int32 `json:"total_page"`
Total int32 `json:"total"`
}
2 years ago
type Integer interface {
~int | ~int32
}
2 years ago
// 用于对一个切片分页
2 years ago
func PageToSlice[T Integer](page, pageSize, total T) (begin, end T) {
2 years ago
if page < DefaultPage {
page = DefaultPage
}
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
}
// 用于分页查询
2 years ago
func PageToOffset[T Integer](page, pageSize T) (offset, limit T) {
if page < DefaultPage {
page = DefaultPage
}
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
}