paginator: github.com/yassinouider/paginator Index | Examples | Files

package paginator

import "github.com/yassinouider/paginator"

Package paginator provides utilities to setup a paginator within the context of a http request.

Code:

handler := func(w http.ResponseWriter, r *http.Request) {
    p := paginator.New(r)

    customers, total, _ := getFakeDataStore().FindCustomers(p.Limit(), p.Offset())

    res := map[string]interface{}{
        "data":       customers,
        "pagination": p.SetCount(len(customers)).SetTotal(total),
    }

    b, _ := json.MarshalIndent(res, "", " ")

    w.Header().Set("Content-Type", "application/json")
    w.Write(b)
}

req := httptest.NewRequest("GET", "http://example.com/customers?page=3&per_page=2", nil)
w := httptest.NewRecorder()
handler(w, req)

resp := w.Result()
body, _ := ioutil.ReadAll(resp.Body)

fmt.Println(string(body))

Output:

{
 "data": [
  "User 5",
  "User 6"
 ],
 "pagination": {
  "total": 7,
  "count": 2,
  "per_page": 2,
  "current_page": 3,
  "total_page": 4
 }
}

Index

Examples

Package Files

paginator.go

Variables

var (
    PerPage     = 50
    PerPageMax  = 1000
    PerPageName = "per_page"
    PageName    = "page"
)

Default values

func Offset Uses

func Offset(page, limit int) int

Code:

page := 3
limit := 10

result := paginator.Offset(page, limit)

fmt.Printf("%d", result)

Output:

20

func TotalPage Uses

func TotalPage(total, limit int) int

type Paginator Uses

type Paginator struct {
    Total       int `json:"total"`
    Count       int `json:"count"`
    PerPage     int `json:"per_page"`
    CurrentPage int `json:"current_page"`
    TotalPage   int `json:"total_page"`
}

func New Uses

func New(r *http.Request) *Paginator

New Instantiates a Paginator struct for the current http request.

func (*Paginator) Limit Uses

func (p *Paginator) Limit() int

func (*Paginator) Offset Uses

func (p *Paginator) Offset() int

Offset Returns the current offset.

func (*Paginator) SetCount Uses

func (p *Paginator) SetCount(count int) *Paginator

func (*Paginator) SetTotal Uses

func (p *Paginator) SetTotal(total int) *Paginator

Package paginator imports 4 packages (graph). Updated 2019-07-21. Refresh now. Tools for package owners.