1 Star 1 Fork 1

goeoeo / ant-api

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
pager.go 2.03 KB
一键复制 编辑 原始数据 按行查看 历史
goeoeo 提交于 2019-11-29 14:26 . ant-api初始化
package entitys
import (
"encoding/json"
"errors"
"reflect"
)
type Pager struct {
Page int //当前页
PageSize int //页大小 ,页大小 小于 0 返回所有数据
Total int64 //总量
SliceData interface{} //切片源数据
}
//切片分页 pageSize=-1 返回全部数据
func (this *Pager) DoPage() error {
if this.SliceData == nil {
return nil
}
var (
resSlice []interface{}
arrSlice []interface{}
start int64
end int64
err error
content []byte
)
if arrSlice, err = this.ToSlice(this.SliceData); err != nil {
return err
}
this.Total = int64(len(arrSlice))
//分页大小=-1 或者 当前页大小不大于0 不进行分页处理
if this.PageSize == -1 || this.Page <= 0 {
return nil
}
start = int64((this.Page - 1) * this.PageSize)
end = int64(this.Page * this.PageSize)
if end > this.Total {
end = this.Total
}
for start < end {
resSlice = append(resSlice, arrSlice[start])
start++
}
if content, err = json.Marshal(resSlice); err != nil {
return err
}
return json.Unmarshal(content, this.SliceData)
}
func (this *Pager) SetSliceData(data interface{}) *Pager {
this.SliceData = data
return this
}
//页大小
func (this *Pager) Size() int {
//分页量小于0,返回全部数据
if this.PageSize < 0 {
return int(this.Total)
}
return this.PageSize
}
//偏移量
func (this *Pager) Offset() int {
if this.PageSize < 0 {
return 0
}
offset := (this.Page - 1) * this.PageSize
if offset < 0 {
offset = 0
}
return offset
}
//slice interface 变数组
func (this *Pager) ToSlice(arr interface{}) ([]interface{}, error) {
v := reflect.ValueOf(arr)
if v.Kind() != reflect.Ptr {
return []interface{}{}, errors.New("分页源数据必须为切片指针")
}
ve := reflect.ValueOf(arr).Elem()
if ve.Kind() != reflect.Slice {
return []interface{}{}, errors.New("分页源数据必须为切片指针.")
}
l := ve.Len()
ret := make([]interface{}, l)
for i := 0; i < l; i++ {
ret[i] = ve.Index(i).Interface()
}
return ret, nil
}
Go
1
https://gitee.com/goeoeo/ant-api.git
git@gitee.com:goeoeo/ant-api.git
goeoeo
ant-api
ant-api
a4d54182c883

搜索帮助

53164aa7 5694891 3bd8fe86 5694891