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.
60 lines
1.0 KiB
60 lines
1.0 KiB
2 years ago
|
package pagination
|
||
|
|
||
|
import "math"
|
||
|
|
||
|
const (
|
||
|
DefaultPage = 1
|
||
|
MinPageSize = 10
|
||
|
MaxPageSize = 100
|
||
|
)
|
||
|
|
||
|
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 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
|
||
|
}
|