序
本文次要钻研一下 gost 的 Pager
Pager
gost/hash/page/pager.go
// Pager is the abstraction for pagination usage.
type Pager interface {
// GetOffset will return the offset
GetOffset() int
// GetPageSize will return the page size
GetPageSize() int
// GetTotalPages will return the number of total pages
GetTotalPages() int
// GetData will return the data
GetData() []interface{}
// GetDataSize will return the size of data.
// Usually it's len(GetData())
GetDataSize() int
// HasNext will return whether has next page
HasNext() bool
// HasData will return whether this page has data.
HasData() bool}
Pager 接口定义了 GetOffset、GetPageSize、GetTotalPages、GetData、GetDataSize、HasNext、HasData 办法
Page
gost/hash/page/page.go
// Page is the default implementation of Pager interface
type Page struct {
requestOffset int
pageSize int
totalSize int
data []interface{}
totalPages int
hasNext bool
}
// GetOffSet will return the offset
func (d *Page) GetOffset() int {return d.requestOffset}
// GetPageSize will return the page size
func (d *Page) GetPageSize() int {return d.pageSize}
// GetTotalPages will return the number of total pages
func (d *Page) GetTotalPages() int {return d.totalPages}
// GetData will return the data
func (d *Page) GetData() []interface{} {return d.data}
// GetDataSize will return the size of data.
// it's len(GetData())
func (d *Page) GetDataSize() int {return len(d.GetData())
}
// HasNext will return whether has next page
func (d *Page) HasNext() bool {return d.hasNext}
// HasData will return whether this page has data.
func (d *Page) HasData() bool {return d.GetDataSize() > 0
}
Page 定义了 requestOffset、pageSize、totalSize、data、totalPages、hasNext 属性;它实现了 Pager 接口,其 GetDataSize 办法返回的是 len(d.GetData());其 HasData 办法应用
d.GetDataSize() > 0
来判断
NewPage
gost/hash/page/page.go
// NewPage will create an instance
func NewPage(requestOffset int, pageSize int,
data []interface{}, totalSize int) *Page {
remain := totalSize % pageSize
totalPages := totalSize / pageSize
if remain > 0 {totalPages++}
hasNext := totalSize-requestOffset-pageSize > 0
return &Page{
requestOffset: requestOffset,
pageSize: pageSize,
data: data,
totalSize: totalSize,
totalPages: totalPages,
hasNext: hasNext,
}
}
NewPage 办法依据 requestOffset、pageSize、data、totalSize 来结构 Page;它会计算 totalPages、hasNext
实例
gost/hash/page/page_test.go
func TestNewDefaultPage(t *testing.T) {data := make([]interface{}, 10)
page := NewPage(121, 10, data, 499)
assert.Equal(t, 10, page.GetDataSize())
assert.Equal(t, 121, page.GetOffset())
assert.Equal(t, 10, page.GetPageSize())
assert.Equal(t, 50, page.GetTotalPages())
assert.Equal(t, data, page.GetData())
assert.True(t, page.HasNext())
assert.True(t, page.HasData())
page = NewPage(492, 10, data, 499)
assert.False(t, page.HasNext())
}
小结
gost 的 Pager 接口定义了 GetOffset、GetPageSize、GetTotalPages、GetData、GetDataSize、HasNext、HasData 办法;Page 定义了 requestOffset、pageSize、totalSize、data、totalPages、hasNext 属性;它实现了 Pager 接口。
doc
- gost