序
本文主要研究一下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接口。