Simple, fast and safe pagination for Go.
Requires Go 1.25+.
package main
import (
"context""log""github.com/junsred/pagination"
)
funcmain() {
items:= []*pagination.Item[int, string]{
{Key: 1, Value: "Item 1"},
{Key: 2, Value: "Item 2"},
{Key: 3, Value: "Item 3"},
}
p:=pagination.New(pagination.FromSlice(items), 0)
forpage, err:=rangep.Pages(context.Background(), 2) {
iferr!=nil {
log.Fatal(err)
}
for_, item:=rangepage.Items {
log.Println(item.Value)
}
}
}FromSlice covers in-memory data. For a database (or anything else), pass a fetch function with the same shape:
funcfetch(ctx context.Context, limitint, lastKey*int) ([]*pagination.Item[int, string], bool, error) {
// SELECT ... WHERE key > lastKey ORDER BY key LIMIT limitreturnpage, hasNext, nil
}
p:=pagination.New(fetch, 0)
page, err:=p.Paginate(ctx, 20)