Implement pagination sorting and filtering
Implement pagination sorting and filtering
List endpoints need a bounded response size and an explicit ordering. Filter the authorized collection first, sort by a supported field with a unique tie breaker, then select the requested page. Offset pagination selects by position; a cursor instead identifies a boundary in the ordering. Neither should expose records outside the caller’s permissions.
package main
import ( "errors" "fmt" "sort")
type Item struct{ ID, Price int }
func page(items []Item, min, offset, limit int) ([]Item, error) { if offset < 0 || limit < 1 || limit > 100 { return nil, errors.New("invalid page") } filtered := []Item{} for _, it := range items { if it.Price >= min { filtered = append(filtered, it) } } sort.Slice(filtered, func(i, j int) bool { a, b := filtered[i], filtered[j] if a.Price == b.Price { return a.ID < b.ID } return a.Price < b.Price }) if offset >= len(filtered) { return []Item{}, nil } n := len(filtered) - offset if n > limit { n = limit } return filtered[offset : offset+n], nil}func main() { items := []Item{{3, 20}, {2, 10}, {1, 20}, {4, 5}} p, e := page(items, 10, 1, 2) if e != nil { panic(e) } fmt.Println(p, items[0].ID)}Here price is primary and unique ID breaks ties. The filtered slice owns its elements; sorting it does not rearrange the input. Reject negative offsets and limits outside 1–100. Computing the remaining length before adding avoids overflow from an unbounded offset. In a database perform filtering and ordering there, with an appropriate index.
Expected output:
[{1 20} {3 20}] 3Validate a cursor boundary
package main
import ( "fmt")
func after(price, id, lastPrice, lastID int) bool { return price > lastPrice || price == lastPrice && id > lastID}func main() { fmt.Println(after(20, 3, 20, 1), after(20, 1, 20, 1), after(10, 9, 20, 1))}The comparison must match the sort order exactly. A real opaque cursor encodes both fields and binds the filter and ordering; validate it and enforce authorization on every page. Offset pagination can skip or repeat rows when earlier records are inserted or deleted; cursors reduce that problem but do not guarantee a consistent snapshot during changes.
Expected output:
true false falseTry it locally
Use page with items {ID:1,Price:5} and {ID:2,Price:8}. Request min=6, offset=0, limit=1, then offset=99 and then limit=0. Print the first item, empty-page length and whether the invalid limit returned an error.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
REST API 04: Implement pagination sorting and filtering
Check the lesson objective before moving on.
Why include a unique ID in the sort?
When should authorization filtering happen?