简单的分页工具,只要结构体符合下面的要求,就可以使用该工具解析并填充。
- 被解析的数据必须是结构体
- 结构体必须含有可导出的:
- int 类型:
PageNum
or Num
- int 类型:
PageSize
or Size
- string 类型:
OrderBy
- bool 类型
IsDescending
or Descending
- string 类型:
Qeury
or SearchKey
字段
比如说这样
type testRequest struct {
PageNum int
PageSize int
OrderBy string
IsDescending bool
KeyWords string
SearchKey string
CustomField string
}
- 这些必须字段可以成为一个新的结构体被名在
Page
或 Pagination
的字段下
比如说这样:
type SearchDialogCasesRequest struct {
Page *PaginationRequest
}
type PaginationRequest struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
PageNum int64 `protobuf:"varint,1,opt,name=page_num,json=pageNum,proto3" json:"page_num,omitempty"`
PageSize int64 `protobuf:"varint,2,opt,name=page_size,json=pageSize,proto3" json:"page_size,omitempty"`
OrderBy string `protobuf:"bytes,3,opt,name=order_by,json=orderBy,proto3" json:"order_by,omitempty"`
IsDescending bool `protobuf:"varint,4,opt,name=is_descending,json=isDescending,proto3" json:"is_descending,omitempty"`
SearchKey string `protobuf:"bytes,5,opt,name=search_key,json=searchKey,proto3" json:"search_key,omitempty"`
}
- 被导出的数据必须是结构体
- 被导出的结构体中必须含有
PageNum
, PageSize
和 Total
字段
Usage example
import "github.com/uptutu/pagination"
type ListSubscribeEntitiesRequest {
PageNum int64
PageSize int64
OrderBy string
IsDescending bool
Query string
MyData interface{}
}
type ListSubscribeEntitiesResponse {
Total int64
PageNum int64
LastPage int64
PageSize int64
Data string
}
func (s *SubscribeService) ListSubscribeEntities(ctx context.Context, req *pb.ListSubscribeEntitiesRequest) (*pb.ListSubscribeEntitiesResponse, error) {
page, err := pagination.Parse(req)
fmt.Println(page)
page.Required()
page.Limit()
page.Offset()
page.IsDescending
page.Query
page.OrderBy
count := db.Find(data).Count()
page.SetTotal(count)
resp := &ListSubscribeEntitiesResponse{}
resp.Data = "一些数据"
page.FillResponse(resp)
}
func Required
Used to determine if the paging request passed meets the paging needs
Judgement conditions:
func (p Page) Required() bool {
return p.Num > 0 && p.Size > 0
}
func Limit
if no limit set this will return the default value.
func (p Page) Limit() int32 {
if p.Size != 0 {
return uint32(p.Size)
}
return uint32(p.defaultSize)
}
func Offset
count the offset of the current page
func (p Page) Offset() int32 {
if p.Num <= 0 {
return 0
}
return uint32((p.Num - 1) * p.Size)
}
func FillResponse
Automatic padding of paginated data to match paginated responsive design.