52 lines
1.2 KiB
Go
52 lines
1.2 KiB
Go
package common
|
|
|
|
import "time"
|
|
|
|
// Pagination 分页请求参数
|
|
type Pagination struct {
|
|
Page int `form:"page" json:"page" binding:"min=1"`
|
|
PageSize int `form:"page_size" json:"page_size" binding:"min=1,max=100"`
|
|
}
|
|
|
|
// PaginatedResult 分页响应
|
|
type PaginatedResult struct {
|
|
Items interface{} `json:"items"`
|
|
Total int64 `json:"total"`
|
|
Page int `json:"page"`
|
|
PageSize int `json:"page_size"`
|
|
TotalPages int `json:"total_pages"`
|
|
}
|
|
|
|
// DefaultPagination 默认分页(未传参时使用)
|
|
func (p *Pagination) DefaultPagination() {
|
|
if p.Page < 1 {
|
|
p.Page = 1
|
|
}
|
|
if p.PageSize < 1 || p.PageSize > 100 {
|
|
p.PageSize = 20
|
|
}
|
|
}
|
|
|
|
// Offset 计算 SQL offset
|
|
func (p *Pagination) Offset() int {
|
|
return (p.Page - 1) * p.PageSize
|
|
}
|
|
|
|
// NewPaginatedResult 构建分页响应
|
|
func NewPaginatedResult(items interface{}, total int64, page, pageSize int) *PaginatedResult {
|
|
totalPages := int(total) / pageSize
|
|
if int(total)%pageSize > 0 {
|
|
totalPages++
|
|
}
|
|
return &PaginatedResult{
|
|
Items: items,
|
|
Total: total,
|
|
Page: page,
|
|
PageSize: pageSize,
|
|
TotalPages: totalPages,
|
|
}
|
|
}
|
|
|
|
// 固定时间格式,前后端统一
|
|
const TimeFormat = time.RFC3339
|