mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
A page such as 9223372036854775807 passed every pagination check, so (page-1)*pageSize wrapped around. With an even page size the offset became negative and PostgreSQL rejected the query with "OFFSET must not be negative"; paths that slice in memory (paginateSlice, balance history merge) panicked with a negative slice bound. Both surfaced as HTTP 500 on list endpoints such as /api/v1/admin/users, /api/v1/usage, /api/v1/keys and /api/v1/admin/payment/orders. - PaginationParams.Offset saturates Page at MaxInt/limit, so offset and offset+limit both stay within int. - ParsePagination clamps page the same way, which covers the repositories that compute (page-1)*pageSize themselves. - The prompt audit event list and the OpenAI token stats filter parse page on their own; they now reject an overflowing page with 400, like other invalid pagination input there.
86 lines
1.7 KiB
Go
86 lines
1.7 KiB
Go
// Package pagination provides types and helpers for paginated responses.
|
|
package pagination
|
|
|
|
import (
|
|
"math"
|
|
"strings"
|
|
)
|
|
|
|
const (
|
|
SortOrderAsc = "asc"
|
|
SortOrderDesc = "desc"
|
|
)
|
|
|
|
// PaginationParams 分页参数
|
|
type PaginationParams struct {
|
|
Page int
|
|
PageSize int
|
|
SortBy string
|
|
SortOrder string
|
|
}
|
|
|
|
// PaginationResult 分页结果
|
|
type PaginationResult struct {
|
|
Total int64
|
|
Page int
|
|
PageSize int
|
|
Pages int
|
|
}
|
|
|
|
// DefaultPagination 默认分页参数
|
|
func DefaultPagination() PaginationParams {
|
|
return PaginationParams{
|
|
Page: 1,
|
|
PageSize: 20,
|
|
SortOrder: SortOrderDesc,
|
|
}
|
|
}
|
|
|
|
// Offset 计算偏移量
|
|
func (p PaginationParams) Offset() int {
|
|
if p.Page < 1 {
|
|
p.Page = 1
|
|
}
|
|
limit := p.Limit()
|
|
// Saturate the page so both the offset and offset+limit stay within int.
|
|
if p.Page > math.MaxInt/limit {
|
|
p.Page = math.MaxInt / limit
|
|
}
|
|
return (p.Page - 1) * limit
|
|
}
|
|
|
|
// Limit 获取限制数
|
|
func (p PaginationParams) Limit() int {
|
|
if p.PageSize < 1 {
|
|
return 20
|
|
}
|
|
if p.PageSize > 1000 {
|
|
return 1000
|
|
}
|
|
return p.PageSize
|
|
}
|
|
|
|
// NormalizeSortOrder normalizes sort order to asc/desc and falls back to defaultOrder.
|
|
func NormalizeSortOrder(order string, defaultOrder string) string {
|
|
switch strings.ToLower(strings.TrimSpace(defaultOrder)) {
|
|
case SortOrderAsc:
|
|
defaultOrder = SortOrderAsc
|
|
default:
|
|
defaultOrder = SortOrderDesc
|
|
}
|
|
|
|
switch strings.ToLower(strings.TrimSpace(order)) {
|
|
case SortOrderAsc:
|
|
return SortOrderAsc
|
|
case SortOrderDesc:
|
|
return SortOrderDesc
|
|
default:
|
|
return defaultOrder
|
|
}
|
|
}
|
|
|
|
// NormalizedSortOrder returns the normalized sort order using defaultOrder as fallback.
|
|
func (p PaginationParams) NormalizedSortOrder(defaultOrder string) string {
|
|
return NormalizeSortOrder(p.SortOrder, defaultOrder)
|
|
}
|