Documentation
¶
Overview ¶
Package pagination provides the offset and cursor pagination types and opaque cursor codecs shared by the database and request packages. It holds only data types and small helpers, and depends on neither net/http nor a database.
request.Page and request.Cursor in arkoren.dev/core/http/request read query parameters into PageParams and CursorParams. Both types can also be built by hand and checked with their Normalize methods, which apply defaults (zero uses the default), clamp values, and validate the configuration.
CursorPaginate builds a Cursor with one encoder for both cursors; CursorPaginateFunc takes separate next and previous encoders, for cursors that carry a direction. With arkoren.dev/core/service/database, the Paginate and CursorPaginate methods of Database run the queries and call these.
CursorEncode and CursorDecode produce plain base64 JSON that a client can forge. A CursorCodec signs cursors with HMAC-SHA256 instead, using key.Shared values of exactly MinSecretLength bytes and optional previous keys for rotation. Database.CursorPaginate selects one through database.Builder.CursorCodec. Both encoders reject tokens longer than the decoders' 4096-byte limit with ErrCursorEncode, including the signature overhead for signed cursors. A successful encode therefore does not issue an immediately oversized token. A zero CursorCodec is invalid and reports an encoding error instead of panicking; construct it with NewCursorCodec before sharing it. Page and Cursor construction copy their outer item slices, not referenced item objects. Items is an eager collection.Slice with local Map, Filter, and GroupBy operations. These operations inspect only the current window; they neither fetch more items nor recompute server totals or cursor boundaries. Cursor helpers retain PerPage as metadata without normalizing or trimming items. Their encoders run next then previous, only when requested on nonempty items, and can return a partial result alongside an error.
Database keyset pagination requires non-NULL ordered values throughout the selected dataset. It rejects observed NULL keys, including nullable SQL representations, but cannot detect NULL rows that a SQL seek excludes. Use non-nullable ordering keys or explicitly filter out NULL rows; this package does not add NULL ordering to SQL queries.
Zero configuration fields use the defaults. Page and per-page defaults may use any integer and are normalized to positive returned values. A negative maximum makes Normalize return ErrInvalidConfig.
Example:
codec, err := pagination.NewCursorCodec(secret)
if err != nil {
return err
}
db := database.New(driver, func(databaseClient *database.Builder) {
databaseClient.CursorCodec(codec)
})
_ = db.Driver()
Index ¶
Examples ¶
Constants ¶
const MinSecretLength = 32
MinSecretLength is the required length in bytes of every CursorCodec secret. The name is retained for compatibility; key.Shared accepts exactly 32 bytes, not arbitrary longer material.
Example:
raw := []byte("0123456789abcdef0123456789abcdef") // Example material only.
if len(raw) != pagination.MinSecretLength {
return errors.New("cursor key must contain exactly 32 bytes")
}
Variables ¶
var ErrCursorDecode = problem.New(func(details *problem.Builder) {
details.Type("tag:arkoren.dev,2026-09:core:pagination:cursor-decode")
details.Title("Invalid cursor")
details.Detail("The cursor could not be decoded.")
details.Status(statusBadRequest)
})
ErrCursorDecode is returned when a cursor string fails to decode. It is a problem.Details, so a handler that returns it responds 400 Bad Request. Callers match it, or an error wrapping it, with errors.Is.
Example:
failure := pagination.ErrCursorDecode.Derive(func(details *problem.Builder) {
details.Detail("The request cannot be completed.")
})
_ = failure.Status()
var ErrCursorEncode = errors.New("failed to encode cursor")
ErrCursorEncode classifies serialization, callback, invalid-codec, and token size failures. Wrapped callback and serialization causes remain discoverable with errors.Is/errors.As; never treat a partial cursor result as successful.
Example:
_, err := pagination.CursorEncode(make(chan int))
if errors.Is(err, pagination.ErrCursorEncode) {
fmt.Println("cursor could not be encoded")
}
var ErrInvalidConfig = errors.New("invalid pagination config")
ErrInvalidConfig is returned when a pagination maximum is less than one after zero defaults are completed. It is a configuration failure, not a request overflow; callers match it through errors.Is.
Example:
_, err := (pagination.PageParams{}).Normalize(pagination.WithMaxPerPage(-1))
if errors.Is(err, pagination.ErrInvalidConfig) {
fmt.Println("configure a positive maximum")
}
var ErrInvalidSecret = errors.New("cursor signing secret is invalid")
ErrInvalidSecret reports a zero current/previous key.Shared supplied to NewCursorCodec, or Encode on an unconstructed zero codec. The key package enforces MinSecretLength before publishing nonzero application material.
Example:
_, err := pagination.NewCursorCodec(key.Shared{})
if errors.Is(err, pagination.ErrInvalidSecret) {
fmt.Println("configure a cursor key")
}
var ErrPageOverflow = problem.New(func(details *problem.Builder) {
details.Type("tag:arkoren.dev,2026-09:core:pagination:page-overflow")
details.Title("Page out of range")
details.Detail("The requested page is out of range.")
details.Status(statusBadRequest)
})
ErrPageOverflow is returned when a page is above Config.MaxPage or the offset of a page would overflow an int. It is a problem.Details, so a handler that returns it responds 400 Bad Request. Callers match it with errors.Is.
Example:
failure := pagination.ErrPageOverflow.Derive(func(details *problem.Builder) {
details.Detail("The request cannot be completed.")
})
_ = failure.Status()
Functions ¶
func CursorDecode ¶
CursorDecode decodes an opaque cursor string back into a typed value. It reverses the encoding performed by CursorEncode. Cursors are not signed: treat decoded values as untrusted client input. Inputs above 4096 bytes, invalid base64url, or incompatible JSON return an error matching ErrCursorDecode. A valid token supplies data, not authorization.
Example:
cursor, err := pagination.CursorEncode(42)
if err != nil {
return err
}
value, err := pagination.CursorDecode[int](cursor)
if err != nil {
return err
}
_ = value // 42.
func CursorEncode ¶
CursorEncode encodes a value into an opaque cursor string using JSON serialization and base64url encoding. Serialization failures wrap ErrCursorEncode. A result longer than the 4096-byte CursorDecode limit fails with ErrCursorEncode instead of returning an unusable cursor.
Example:
cursor, err := pagination.CursorEncode(42)
if err != nil {
return err
}
position, err := pagination.CursorDecode[int](cursor)
if err != nil {
return err
}
_ = position
func Offset ¶
Offset returns the number of items before page, for use as a query OFFSET. page and perPage are one-based values from request.Page. This unchecked arithmetic helper expects parameters already accepted by PageParams.Normalize; arbitrary input can overflow or produce a negative offset.
Example:
_ = pagination.Offset(3, 20) // 40.
Types ¶
type Config ¶
type Config struct {
// DefaultPage is the fallback page number when a request omits page.
// Normalize also uses it for explicit zero, then raises negatives to one.
//
// Example:
//
// config := pagination.NewConfig(pagination.WithDefaultPage(2))
// _ = config.DefaultPage // 2.
DefaultPage int
// DefaultPerPage is the fallback page size when a request omits per_page.
// Normalize also uses it for explicit zero, then clamps to positive limits.
//
// Example:
//
// config := pagination.NewConfig(pagination.WithDefaultPerPage(10))
// _ = config.DefaultPerPage // 10.
DefaultPerPage int
// MaxPerPage caps the page size accepted from a request.
// Zero uses 100 during normalization; negative values are invalid.
//
// Example:
//
// config := pagination.NewConfig(pagination.WithMaxPerPage(50))
// _ = config.MaxPerPage // 50.
MaxPerPage int
// MaxPage caps the page number accepted from a request, because a deep
// page forces the database to scan and discard every row before it.
// Zero uses 10000. Raise it with [WithMaxPage] for datasets that need
// deeper offsets, or prefer cursor pagination for them.
//
// Example:
//
// config := pagination.NewConfig(pagination.WithMaxPage(500))
// _ = config.MaxPage // 500.
MaxPage int
}
Config configures offset-based request pagination. Zero fields use the built-in defaults when PageParams.Normalize consumes the configuration. NewConfig itself applies options without validation or zero completion.
Example:
config := pagination.Config{DefaultPerPage: 10, MaxPerPage: 50}
params, err := (pagination.PageParams{}).Normalize(pagination.WithConfig(config))
if err != nil {
return err
}
_ = params.PerPage // 10.
func NewConfig ¶
NewConfig returns the default configuration with opts applied in order. It does not validate the completed value or refill zeros introduced by an option; PageParams.Normalize performs that work. Nil option entries panic.
Example:
config := pagination.NewConfig(pagination.WithDefaultPerPage(10)) _ = config.DefaultPerPage // 10.
type Cursor ¶
type Cursor[T any] struct { // Items contains an eager collection detached from the cursor helper's input. // Referenced objects remain shared, including callback-visible objects. // Transformations affect only this window and leave its tokens unchanged. // // Example: // // page, err := pagination.CursorPaginate([]int{41, 42}, 2, false, false, nil) // if err != nil { // return err // } // _ = page.Items[0] // 41. Items collection.Slice[T] `json:"items"` // PerPage is the maximum number of items in the cursor window. // Cursor helpers retain this caller-supplied metadata without normalization. // // Example: // // page, err := pagination.CursorPaginate([]int{41, 42}, 2, false, false, nil) // if err != nil { // return err // } // _ = page.PerPage // 2. PerPage int `json:"per_page"` // NextCursor identifies the next cursor window when one is available. // Empty means no next token was emitted; clients must pass tokens unchanged. // // Example: // // page, err := pagination.CursorPaginate([]int{41, 42}, 2, true, false, pagination.CursorEncode[int]) // if err != nil { // return err // } // _ = page.NextCursor NextCursor string `json:"next_cursor,omitempty"` // PrevCursor identifies the previous cursor window when one is available. // Empty means no previous token was emitted, including for an empty result. // // Example: // // page, err := pagination.CursorPaginate([]int{41, 42}, 2, false, true, pagination.CursorEncode[int]) // if err != nil { // return err // } // _ = page.PrevCursor PrevCursor string `json:"prev_cursor,omitempty"` }
Cursor represents a cursor-based window without a total count. CursorPaginate snapshots the outer item slice and encodes only requested navigation tokens. Local Items transformations neither fetch another window nor recompute tokens; cursors continue to identify the original window's boundaries.
Example:
page, err := pagination.CursorPaginate([]int{41, 42}, 2, false, false, nil)
if err != nil {
return err
}
_ = page.Items
func CursorPaginate ¶
func CursorPaginate[S ~[]T, T any](items S, perPage int, hasNext, hasPrev bool, encode func(T) (string, error)) (Cursor[T], error)
CursorPaginate creates a new Cursor from the given items. The encode function determines how each item is transformed into an opaque cursor string. The outer item slice is copied; referenced item objects remain shared. PerPage is retained verbatim as metadata, without normalization or trimming. An empty result invokes no encoder and has neither cursor, regardless of flags. Otherwise hasNext encodes the last item before hasPrev encodes the first item. Supply a non-nil encoder for each requested cursor; callback panics propagate. Encoder failures wrap ErrCursorEncode and preserve their cause. The returned result still contains the copied items and any cursor already encoded, so callers must check the error rather than treating that partial result as success.
Example:
page, err := pagination.CursorPaginate([]int{41, 42}, 2, true, false, func(id int) (string, error) {
return pagination.CursorEncode(id)
})
if err != nil {
return err
}
_ = page.NextCursor
Example ¶
ExampleCursorPaginate builds both tokens using the public generic encoder.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
)
func main() {
page, err := pagination.CursorPaginate([]int{41, 42}, 2, true, true, pagination.CursorEncode[int])
if err != nil {
fmt.Println(err)
return
}
fmt.Println(len(page.Items), page.NextCursor != "", page.PrevCursor != "")
}
Output: 2 true true
func CursorPaginateFunc ¶
func CursorPaginateFunc[S ~[]T, T any]( items S, perPage int, hasNext, hasPrev bool, encodeNext, encodePrev func(T) (string, error), ) (Cursor[T], error)
CursorPaginateFunc creates a new Cursor like CursorPaginate but with separate encoders: encodeNext turns the final item into the next cursor and encodePrev turns the first item into the previous cursor. Use it when the two cursors must carry different information, such as a direction. Ownership, unnormalized metadata, callback timing, and partial-error results follow CursorPaginate. Encoders read the captured outer slice, so changing the caller's slice entries during encodeNext does not replace encodePrev's boundary. Referenced item objects and callback captures are still shared.
Example:
page, err := pagination.CursorPaginateFunc([]int{41, 42}, 2, true, true,
func(id int) (string, error) {
return pagination.CursorEncode(map[string]any{"id": id, "backward": false})
},
func(id int) (string, error) {
return pagination.CursorEncode(map[string]any{"id": id, "backward": true})
})
if err != nil {
return err
}
_ = page.PrevCursor
Example ¶
ExampleCursorPaginateFunc keeps forward and backward boundary metadata separate while leaving the caller's original order unchanged.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
)
func main() {
page, err := pagination.CursorPaginateFunc([]int{41, 42}, 2, true, true,
func(id int) (string, error) {
return fmt.Sprintf("next-%d", id), nil
},
func(id int) (string, error) {
return fmt.Sprintf("previous-%d", id), nil
})
if err != nil {
fmt.Println(err)
return
}
fmt.Println(page.NextCursor, page.PrevCursor)
}
Output: next-42 previous-41
type CursorCodec ¶
type CursorCodec struct {
// contains filtered or unexported fields
}
CursorCodec encodes and decodes cursors like CursorEncode and CursorDecode, with an HMAC-SHA256 signature so a client cannot forge or alter a cursor. Without it a client can craft any position; with it only tokens signed by one of the configured keys are accepted. Signing does not encrypt values or enforce authorization, tenant/filter binding, or expiry; applications must check those policies themselves after decoding.
A signed cursor is base64url(payload) + "." + base64url(mac). The MAC covers a version prefix and the encoded payload and is checked before the payload is parsed. Signed and unsigned cursors are not interchangeable: a codec rejects unsigned cursors, and CursorDecode rejects signed ones.
A constructed codec is immutable and safe for concurrent use. The zero codec is invalid: Encode returns ErrCursorEncode and ErrInvalidSecret, while Decode rejects every token with ErrCursorDecode. Obtain one through NewCursorCodec.
Example:
codec, err := pagination.NewCursorCodec(material)
if err != nil {
return err
}
cursor, err := codec.Encode(42)
if err != nil {
return err
}
_ = cursor
Example ¶
ExampleCursorCodec demonstrates typed construction and signed round-tripping without provisioning random material or accessing a network or secret file.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
"arkoren.dev/foundation/key"
)
func main() {
// Fixed example material only; provision a private key for real applications.
material, err := key.NewShared([]byte("0123456789abcdef0123456789abcdef"))
if err != nil {
fmt.Println(err)
return
}
codec, err := pagination.NewCursorCodec(material)
if err != nil {
fmt.Println(err)
return
}
cursor, err := codec.Encode(42)
if err != nil {
fmt.Println(err)
return
}
value, err := codec.Decode[int](cursor)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(value)
}
Output: 42
func NewCursorCodec ¶
NewCursorCodec returns a codec that signs with secret and also accepts cursors signed with any previous secret, which allows rotation: deploy the new secret first with the old one in previous, and drop the old one once the application's retention policy no longer accepts its cursors. The codec supplies no built-in expiration time or expiry validation.
Every secret must be a validated key.Shared. Zero current or previous values return ErrInvalidSecret. Load or parse material through the key package. HKDF-SHA256 derives purpose-bound keys without retaining the original secrets. Provision separate material for unrelated purposes.
Example:
material, err := key.LoadShared("cursor.key")
if err != nil {
return err
}
codec, err := pagination.NewCursorCodec(material)
if err != nil {
return err
}
_ = codec
func (*CursorCodec) Decode ¶
func (codec *CursorCodec) Decode[T any](cursor string) (T, error)
Decode verifies the signature of cursor and, only when it matches one of the codec's secrets, unmarshals the payload into a T. An oversized, unsigned, malformed, or tampered cursor returns an error matching ErrCursorDecode without parsing its payload.
Example:
codec, err := pagination.NewCursorCodec(material)
if err != nil {
return err
}
cursor, err := codec.Encode(42)
if err != nil {
return err
}
value, err := codec.Decode[int](cursor)
if err != nil {
return err
}
_ = value // 42.
func (*CursorCodec) Encode ¶
func (codec *CursorCodec) Encode[T any](value T) (string, error)
Encode serializes value as JSON and returns it as a signed cursor. Serialization failures wrap ErrCursorEncode. The complete signed token must fit Decode's 4096-byte limit; larger values return ErrCursorEncode instead of issuing a cursor that Decode cannot accept. An unconstructed zero codec returns errors matching both ErrCursorEncode and ErrInvalidSecret, without attempting to serialize value.
Example:
// Fixed example material only; provision a private key for real applications.
material, err := key.NewShared([]byte("0123456789abcdef0123456789abcdef"))
if err != nil {
return err
}
codec, err := pagination.NewCursorCodec(material)
if err != nil {
return err
}
cursor, err := codec.Encode(42)
if err != nil {
return err
}
_ = cursor
type CursorConfig ¶
type CursorConfig struct {
// DefaultPerPage is the fallback page size when a request omits per_page.
// Zero uses 25 at normalization, which then applies positive size limits.
//
// Example:
//
// config := pagination.NewCursorConfig(pagination.WithCursorDefaultPerPage(10))
// _ = config.DefaultPerPage // 10.
DefaultPerPage int
// MaxPerPage caps the page size accepted from a request.
// Zero uses 100 at normalization; negative values yield ErrInvalidConfig.
//
// Example:
//
// config := pagination.NewCursorConfig(pagination.WithCursorMaxPerPage(50))
// _ = config.MaxPerPage // 50.
MaxPerPage int
}
CursorConfig configures cursor-based request pagination. Zero fields use built-in defaults when CursorParams.Normalize consumes it. Construction alone neither completes missing fields nor validates a supplied maximum.
Example:
config := pagination.CursorConfig{DefaultPerPage: 10, MaxPerPage: 50}
params, err := (pagination.CursorParams{}).Normalize(pagination.WithCursorConfig(config))
if err != nil {
return err
}
_ = params.PerPage // 10.
func NewCursorConfig ¶
func NewCursorConfig(opts ...CursorOption) CursorConfig
NewCursorConfig returns the default configuration with opts applied in order. It does not normalize or validate the result; CursorParams.Normalize owns those checks. Nil entries panic; expanded nil/empty slices make no changes.
Example:
config := pagination.NewCursorConfig(pagination.WithCursorDefaultPerPage(10)) _ = config.DefaultPerPage // 10.
type CursorOption ¶
type CursorOption func(*CursorConfig)
CursorOption changes one CursorConfig setting. Options run synchronously in order on a fresh value. CursorParams.Normalize completes zero fields and validates maxima; a nil option entry panics.
Example:
options := []pagination.CursorOption{pagination.WithCursorMaxPerPage(50)}
config := pagination.NewCursorConfig(options...)
_ = config.MaxPerPage
func WithCursorConfig ¶
func WithCursorConfig(config CursorConfig) CursorOption
WithCursorConfig replaces the whole configuration. Later options still apply. The struct is captured by value. Zero fields are completed by Normalize, which also rejects negative maxima; construction itself does not validate.
Example:
config := pagination.NewCursorConfig(pagination.WithCursorConfig(pagination.CursorConfig{MaxPerPage: 50}))
_ = config.MaxPerPage // 50.
func WithCursorDefaultPerPage ¶
func WithCursorDefaultPerPage(defaultPerPage int) CursorOption
WithCursorDefaultPerPage sets CursorConfig.DefaultPerPage. Normalize uses this fallback for an omitted/zero size, then raises it to one if negative and caps it at MaxPerPage. Zero uses the built-in default of 25.
Example:
config := pagination.NewCursorConfig(pagination.WithCursorDefaultPerPage(10)) _ = config.DefaultPerPage // 10.
func WithCursorMaxPerPage ¶
func WithCursorMaxPerPage(maxPerPage int) CursorOption
WithCursorMaxPerPage sets CursorConfig.MaxPerPage. Normalize caps requested sizes at this maximum. Zero uses 100; a negative maximum yields ErrInvalidConfig rather than removing the cap.
Example:
config := pagination.NewCursorConfig(pagination.WithCursorMaxPerPage(50)) _ = config.MaxPerPage // 50.
type CursorParams ¶
type CursorParams struct {
// Cursor is the opaque cursor string. Empty means the first window.
// Normalize retains it byte-for-byte; the consumer's codec validates it.
//
// Example:
//
// params := pagination.CursorParams{Cursor: "", PerPage: 20}
// _ = params.Cursor // First window, without a continuation token.
Cursor string
// PerPage is the requested window size. Zero means the default size.
// Normalize raises negatives to one and caps the size at MaxPerPage.
//
// Example:
//
// params := pagination.CursorParams{PerPage: 20}
// _ = params.PerPage // 20.
PerPage int
}
CursorParams holds cursor pagination parameters. It can be built by hand or read from a request with request.Cursor. Call CursorParams.Normalize to apply defaults and limits before use. The token stays opaque; normalization neither decodes nor authenticates it.
Example:
params, err := (pagination.CursorParams{PerPage: 20}).Normalize()
if err != nil {
return err
}
_ = params.Cursor // Empty selects the first window.
Example ¶
ExampleCursorParams demonstrates positive window limits without interpreting a continuation token or claiming it supplies authorization.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
)
func main() {
params, err := (pagination.CursorParams{}).Normalize(pagination.WithCursorMaxPerPage(10))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(params.PerPage, params.Cursor == "")
}
Output: 10 true
func (CursorParams) Normalize ¶
func (params CursorParams) Normalize(opts ...CursorOption) (CursorParams, error)
Normalize replaces a zero PerPage with the default from opts, raises values below one to one, and caps PerPage at the maximum. It returns ErrInvalidConfig when the maximum is less than one. The cursor token is retained unchanged and is not decoded or authenticated.
Example:
params, err := (pagination.CursorParams{}).Normalize(pagination.WithCursorDefaultPerPage(10))
if err != nil {
return err
}
_ = params.PerPage // 10.
type Option ¶
type Option func(*Config)
Option changes one Config setting. Options run synchronously in order on a fresh private configuration value. Validation and zero-default completion happen when PageParams.Normalize consumes the result. Nil entries panic when invoked.
Example:
options := []pagination.Option{pagination.WithDefaultPerPage(10), pagination.WithMaxPerPage(50)}
config := pagination.NewConfig(options...)
_ = config.MaxPerPage
func WithConfig ¶
WithConfig replaces the whole configuration. Later options still apply. The struct is captured by value. Zero fields are completed only by Normalize, not by NewConfig; negative maxima are likewise rejected at normalization.
Example:
config := pagination.NewConfig(pagination.WithConfig(pagination.Config{MaxPerPage: 50}))
_ = config.MaxPerPage // 50.
func WithDefaultPage ¶
WithDefaultPage sets Config.DefaultPage. Normalize uses this fallback for an omitted/zero page, then raises values below one to one and enforces MaxPage and representable offset bounds.
Example:
config := pagination.NewConfig(pagination.WithDefaultPage(2)) _ = config.DefaultPage // 2.
func WithDefaultPerPage ¶
WithDefaultPerPage sets Config.DefaultPerPage. Normalize uses this fallback for an omitted/zero size, raises it to one when negative, and caps it at MaxPerPage. Zero selects the built-in fallback.
Example:
config := pagination.NewConfig(pagination.WithDefaultPerPage(10)) _ = config.DefaultPerPage // 10.
func WithMaxPage ¶
WithMaxPage sets Config.MaxPage. Normalize rejects larger pages with ErrPageOverflow. Zero selects 10000; a negative maximum yields ErrInvalidConfig rather than disabling the cap.
Example:
config := pagination.NewConfig(pagination.WithMaxPage(500)) _ = config.MaxPage // 500.
func WithMaxPerPage ¶
WithMaxPerPage sets Config.MaxPerPage. Normalize caps requested sizes at this maximum; zero uses the built-in 100 and a negative maximum yields ErrInvalidConfig instead of disabling the cap.
Example:
config := pagination.NewConfig(pagination.WithMaxPerPage(50)) _ = config.MaxPerPage // 50.
type Page ¶
type Page[T any] struct { // Items contains the current page as an eager collection, detached from the // input supplied to Paginate. Referenced objects are not recursively copied. // Map, Filter, and GroupBy transform only these items, not server metadata. // // Example: // // page := pagination.Paginate([]int{41, 42}, 2, 1, 2) // values := page.Items.Map(func(_ int, id int) string { // return fmt.Sprint(id) // }) // _ = values[0] // "41". Items collection.Slice[T] `json:"items"` // Total is the total number of items across all pages. // Paginate retains it unchanged, including zero or a negative caller value. // // Example: // // page := pagination.Paginate([]int{1}, 21, 1, 10) // _ = page.Total // 21. Total int64 `json:"total"` // PerPage is the maximum number of items in each page. // Paginate raises it to one when needed but does not trim the item slice. // // Example: // // page := pagination.Paginate([]int{1}, 21, 1, 10) // _ = page.PerPage // 10. PerPage int `json:"per_page"` // CurrentPage is the one-based number of the current page. // Paginate retains a request past LastPage rather than inventing new items. // // Example: // // page := pagination.Paginate([]int(nil), 21, 5, 10) // _ = page.CurrentPage // 5. CurrentPage int `json:"current_page"` // LastPage is the one-based number of the final available page. // Paginate computes it from Total and PerPage, with a minimum of one. // // Example: // // page := pagination.Paginate([]int{1}, 21, 1, 10) // _ = page.LastPage // 3. LastPage int `json:"last_page"` }
Page represents an offset-based paginated result set. Paginate constructs its counts and snapshots the outer item slice, leaving referenced objects shared. Items transformations operate only on this window; they do not fetch more items or recompute Total, PerPage, CurrentPage, or LastPage.
Example:
page := pagination.Paginate([]string{"invoice"}, 21, 2, 10)
_ = page.LastPage // 3.
Example ¶
ExamplePage demonstrates mapping only the fetched window while retaining the server's total rather than treating a local projection as a new result set.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
)
func main() {
page := pagination.Paginate([]int{41, 42}, 21, 2, 10)
labels := page.Items.Map(func(_ int, id int) string {
return fmt.Sprintf("invoice-%d", id)
})
fmt.Println(labels.Items(), page.Total, page.LastPage)
}
Output: [invoice-41 invoice-42] 21 3
func Paginate ¶
Paginate creates a new Page from the given items, total count, current page number, and items per page. It computes the last page automatically. A current page below 1 becomes 1; a page past Page.LastPage is kept, so a request beyond the end reports the page it asked for with no items. Per-page values below 1 become 1. LastPage is at least 1 and capped at math.MaxInt, even for totals up to math.MaxInt64; Total is retained unchanged. Items are copied into a new outer slice; values referenced by individual items are shared, not recursively copied. Nil items become a non-nil empty slice. The helper does not trim items to PerPage or fetch missing rows. The returned Items collection supports local transformations without changing the pagination metadata.
page := pagination.Paginate([]string{"invoice"}, 21, 2, 10)
fmt.Println(page.CurrentPage, page.LastPage) // 2 3
type PageParams ¶
type PageParams struct {
// Page is the one-based page number. Zero means the default page.
// Normalize raises negatives to one and rejects values beyond its bounds.
//
// Example:
//
// params := pagination.PageParams{Page: 3, PerPage: 20}
// _ = params.Page // 3.
Page int
// PerPage is the requested page size. Zero means the default size.
// Normalize raises negatives to one and caps the final size at MaxPerPage.
//
// Example:
//
// params := pagination.PageParams{Page: 3, PerPage: 20}
// _ = params.PerPage // 20.
PerPage int
}
PageParams holds offset pagination parameters. It can be built by hand or read from a request with request.Page. Call PageParams.Normalize to apply defaults and limits before use. Normalization does not fetch items and does not mutate the original value.
Example:
params, err := (pagination.PageParams{Page: 3, PerPage: 20}).Normalize()
if err != nil {
return err
}
_ = params.Offset() // 40.
Example ¶
ExamplePageParams demonstrates normalized offset arithmetic before query use.
package main
import (
"fmt"
"arkoren.dev/core/pagination"
)
func main() {
params, err := (pagination.PageParams{Page: 3, PerPage: 20}).Normalize()
if err != nil {
fmt.Println(err)
return
}
fmt.Println(params.Offset())
}
Output: 40
func (PageParams) Normalize ¶
func (params PageParams) Normalize(opts ...Option) (PageParams, error)
Normalize replaces zero fields with the defaults from opts, raises values below one to one, and caps PerPage at the maximum. It returns ErrInvalidConfig when a maximum is less than one, and ErrPageOverflow when the page is above Config.MaxPage or its offset would overflow.
Example:
params, err := (pagination.PageParams{Page: 3}).Normalize()
if err != nil {
return err
}
_ = params.Offset() // 50, using the default size of 25.
func (PageParams) Offset ¶
func (params PageParams) Offset() int
Offset returns the number of items before the page, for use as a query OFFSET. It expects normalized parameters. No overflow check is repeated here; callers first use Normalize to establish a positive size/page and a representable result.
Example:
params, err := (pagination.PageParams{Page: 3, PerPage: 20}).Normalize()
if err != nil {
return err
}
_ = params.Offset() // 40.