Files
gochat/pkg/pagination/pagination.go
T
2026-06-04 15:44:48 +08:00

51 lines
1.0 KiB
Go

package pagination
import (
"strconv"
"github.com/gin-gonic/gin"
)
// DefaultPerPage is the default page size.
// Reference: Chatwoot API default pagination (25 items per page)
const DefaultPerPage = 25
const MaxPerPage = 100
// Params holds pagination parameters extracted from request
type Params struct {
Page int
PerPage int
Offset int
}
// Parse extracts pagination params from Gin context query.
// Pattern: Chatwoot controllers use params[:page] and params[:per_page]
func Parse(c *gin.Context) Params {
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
perPage, _ := strconv.Atoi(c.DefaultQuery("per_page", strconv.Itoa(DefaultPerPage)))
if page < 1 {
page = 1
}
if perPage < 1 {
perPage = DefaultPerPage
}
if perPage > MaxPerPage {
perPage = MaxPerPage
}
return Params{
Page: page,
PerPage: perPage,
Offset: (page - 1) * perPage,
}
}
// OffsetToPage converts offset back to page number
func OffsetToPage(offset, perPage int) int {
if perPage <= 0 {
return 1
}
return (offset / perPage) + 1
}