pagination

package module
v0.0.0-...-02c3f02 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 9, 2026 License: Apache-2.0 Imports: 3 Imported by: 0

README

pagination

Standard pagination envelope and query parameter parsing. Keeps list endpoints consistent across the API.

Usage

import "github.com/OpenNSW/core/pagination"

func handleList(w http.ResponseWriter, r *http.Request) {
    rawOffset, rawLimit, err := pagination.ParsePaginationParams(r)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    offset, limit := pagination.ResolvePaginationParams(rawOffset, rawLimit)
    items, total := repo.List(r.Context(), offset, limit)
    page := pagination.NewPageResult(items, total, offset, limit)

    json.NewEncoder(w).Encode(page)
}

ParsePaginationParams reads ?offset= and ?limit= from the query string and returns pointers — nil means the parameter was absent, letting you apply defaults via ResolvePaginationParams.

Defaults and limits

// Apply defaults and enforce the max limit cap without parsing HTTP params
offset, limit := pagination.ResolvePaginationParams(rawOffset, rawLimit)
Parameter Default Max
offset 0
limit 50 100

Response envelope

Page[T] is the JSON envelope returned to clients:

{
  "items": [...],
  "total": 247,
  "offset": 50,
  "limit": 50
}

NewPageResult normalises a nil items slice to an empty array so the JSON response always contains "items": [] rather than "items": null.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ParsePaginationParams

func ParsePaginationParams(r *http.Request) (*int, *int, error)

ParsePaginationParams extracts offset and limit from query parameters.

func ResolvePaginationParams

func ResolvePaginationParams(offset *int, limit *int) (int, int)

ResolvePaginationParams calculates the offset and limit for pagination based on the provided values. If offset or limit are nil, default values are used. The limit is capped at a maximum value.

Types

type Page

type Page[T any] struct {
	Items  []T   `json:"items"`
	Total  int64 `json:"total"`
	Offset int   `json:"offset"`
	Limit  int   `json:"limit"`
}

Page is the standard pagination envelope returned by all list endpoints.

func NewPageResult

func NewPageResult[T any](items []T, total int64, offset, limit int) Page[T]

NewPageResult constructs a Page from items and pagination metadata, ensuring Items is never nil.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL