Skip to content
This repository was archived by the owner on Nov 6, 2021. It is now read-only.

Pagination

B1nj0y edited this page Sep 5, 2017 · 38 revisions

A keyset style pagination

100% offset-free

What's a keyset pagination: http://use-the-index-luke.com/no-offset.

Basic Usage

Take a model named Post as an example. There will be a data type PostPage for pagination:

type PostPage struct {
    WhereString string
    WhereParams []interface{}
    Order       map[string]string
    FirstId     int64
    LastId      int64
    PageNum     int
    PerPage     int
    TotalPages  int
    TotalItems  int64
}

And meanwhile there're three method Current, Next and Previous.

// Current get the current page of PostPage object for pagination
func (_p *PostPage) Current() ([]Post, error)

// Current get the next page of PostPage object for pagination
func (_p *PostPage) Next() ([]Post, error)

// Current get the previous page of PostPage object for pagination 
func (_p *PostPage) Previous() ([]Post, error)

You can init a PostPage at first:

pp := PostPage{Order: map[string]string{"id": "desc"}, PerPage: 5}

Then get the first page:

ps, err := pp.Current()

Then next page:

ps, err = pp.Next()

Or back to previous page:

ps, err = pp.Previous()

Show the current page number:

fmt.Println(pp.PageNum)

Show total pages and total count:

fmt.Println(pp.TotalPages)
fmt.Println(pp.TotalItems)

Add a where clause

You can add a where clause with parameters as a filter when init a PostPage object:

pp := PostPage{
WhereString: "title LIKE ? AND hits > ?", 
WhereParams: []interface{}{"%go-on-rails%", 200}, 
Order: map[string]string{"id": "desc"}, 
PerPage: 5}

Here the WhereString is a ? binding with WhereParams correspondingly.

Clone this wiki locally