41 lines
895 B
Go
41 lines
895 B
Go
package responsex
|
||
|
||
import "math"
|
||
|
||
type Pagination struct {
|
||
Page int64 `json:"page"`
|
||
Size int64 `json:"size"`
|
||
TotalPage int64 `json:"total_page"`
|
||
TotalCount int64 `json:"total_count"`
|
||
}
|
||
|
||
// 计算DB分页偏移量
|
||
// page/size 小于等于 0 时取默认值(page=1,size=10),保证 offset/limit 永远合法
|
||
func GetOffset(page, size int) (offset int, limit int) {
|
||
if page <= 0 {
|
||
page = 1
|
||
}
|
||
if size <= 0 {
|
||
// 默认查10条
|
||
size = 10
|
||
}
|
||
offset = (page - 1) * size
|
||
limit = size
|
||
return
|
||
}
|
||
|
||
// 计算响应分页
|
||
// size 小于等于 0 时不做除法,避免出现负数总页数
|
||
func GetPage(page, size, totalCount int64) Pagination {
|
||
pa := Pagination{}
|
||
var totalPage int64
|
||
if size > 0 {
|
||
totalPage = int64(math.Ceil(float64(totalCount) / float64(size)))
|
||
}
|
||
pa.Page = page
|
||
pa.Size = size
|
||
pa.TotalPage = totalPage
|
||
pa.TotalCount = totalCount
|
||
return pa
|
||
}
|