Gin project: a complete REST API · 5 MIN READ
Paginate with opaque cursors, a bounded limit and a total order; filter only through allow-lists
Serve stable pages of notes with keyset cursors, cap the page size and accept only allow-listed filter and sort parameters.
A GET /notes that returns every row is fine with ten notes and an outage with ten million. Pagination bounds the work per request, but the naive offset version skips or repeats rows when data changes between pages, and a sort parameter pasted into SQL is an injection point. This lesson adds listing, filtering and sorting to the notes API with both failure modes closed.
gin · A MAP OF THE IDEA
- Parse and allow-list query
- Order by key plus id
- Fetch limit plus one
- Return opaque cursor
Useful when
- Pages stay correct while rows are inserted or deleted.
- Each page costs about the same with a composite index.
- Sort input can never become SQL text.
Watch out
- Cursors are readable and forgeable; validate them like any input.
- No random page access or cheap total count with keyset pagination.
Implementation & operation cost: A cursor type, a composite index and an allow-list per sortable field; filters and sorts must be designed, not exposed column by column.
Offset pages drift; key-based pages do not
OFFSET 40 LIMIT 20 asks the database to produce sixty rows and throw away forty, so deep pages get slower as the table grows. Worse, positions are not stable: when a note is inserted at the top between two requests, every row shifts down by one and the next page repeats a note; a delete makes one disappear. Keyset pagination remembers the sort key and ID of the last row returned and asks for rows strictly after that point. With an index on those columns each page costs about the same, and concurrent inserts cannot shift a boundary that is a value rather than a count. The trade-offs are honest ones: no jumping to page 37 and no cheap total count. Offset remains acceptable for small, rarely changing admin tables.
List, filter and sort the notes
parseList is the gate: it rejects malformed query strings and unknown parameters, bounds the limit, checks the sort against the allow-list and decodes the cursor. The store sorts by the chosen key with the ID as tie-breaker, skips everything up to the cursor, and fetches one extra row to learn whether another page exists. The program first shows offset drift on the same data, then walks the cursor pages while a new note arrives, and finally sends invalid queries.
package main
import (
"cmp"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"maps"
"net/http"
"net/http/httptest"
"net/url"
"slices"
"strconv"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
)
type Note struct {
ID string `json:"id"`
Title string `json:"title"`
Pinned bool `json:"pinned"`
CreatedAt time.Time `json:"createdAt"`
}
const (
defaultLimit = 20
maxLimit = 100
)
// The sort allow-list: public name -> direction and key. Nothing else is accepted.
type sortSpec struct {
desc bool
key func(Note) string
}
func createdKey(n Note) string {
// Fixed width, UTC, microseconds: compares correctly as a string.
return n.CreatedAt.UTC().Format("2006-01-02T15:04:05.000000Z")
}
var sorts = map[string]sortSpec{
"created": {desc: false, key: createdKey},
"-created": {desc: true, key: createdKey},
"title": {desc: false, key: func(n Note) string { return n.Title }},
}
type cursor struct {
Sort string `json:"s"`
Key string `json:"k"`
ID string `json:"id"`
}
func encodeCursor(c cursor) string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func decodeCursor(s string) (cursor, error) {
var c cursor
b, err := base64.RawURLEncoding.DecodeString(s)
if err != nil || json.Unmarshal(b, &c) != nil || c.ID == "" {
return cursor{}, errors.New("cursor is invalid")
}
return c, nil
}
// compare orders by (key, id); the id tie-breaker makes the order total.
func compare(s sortSpec, aKey, aID, bKey, bID string) int {
c := cmp.Or(cmp.Compare(aKey, bKey), cmp.Compare(aID, bID))
if s.desc {
return -c
}
return c
}
type listQuery struct {
limit int
sort string
pinned *bool
after *cursor
}
func parseList(rawQuery string) (listQuery, error) {
q, err := url.ParseQuery(rawQuery)
if err != nil {
return listQuery{}, errors.New("query string is malformed")
}
allowed := map[string]bool{"limit": true, "cursor": true, "sort": true, "pinned": true}
for _, k := range slices.Sorted(maps.Keys(q)) {
if !allowed[k] {
return listQuery{}, fmt.Errorf("unknown query parameter: %s", k)
}
}
lq := listQuery{limit: defaultLimit, sort: "-created"}
if v := q.Get("limit"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return listQuery{}, errors.New("limit must be a positive integer")
}
lq.limit = min(n, maxLimit)
}
if v := q.Get("sort"); v != "" {
if _, ok := sorts[v]; !ok {
names := slices.Sorted(maps.Keys(sorts))
return listQuery{}, fmt.Errorf("sort must be one of %s", strings.Join(names, ", "))
}
lq.sort = v
}
if v := q.Get("pinned"); v != "" {
b, err := strconv.ParseBool(v)
if err != nil {
return listQuery{}, errors.New("pinned must be true or false")
}
lq.pinned = &b
}
if v := q.Get("cursor"); v != "" {
c, err := decodeCursor(v)
if err != nil {
return listQuery{}, err
}
if q.Get("sort") != "" && c.Sort != lq.sort {
return listQuery{}, errors.New("cursor was issued for a different sort")
}
lq.sort, lq.after = c.Sort, &c
}
return lq, nil
}
type MemoryStore struct {
mu sync.RWMutex
notes []Note
}
func (m *MemoryStore) Add(n Note) {
m.mu.Lock()
defer m.mu.Unlock()
m.notes = append(m.notes, n)
}
// List returns one page and the cursor for the next one ("" when there is none).
func (m *MemoryStore) List(q listQuery) ([]Note, string) {
m.mu.RLock()
all := slices.Clone(m.notes)
m.mu.RUnlock()
spec := sorts[q.sort]
slices.SortFunc(all, func(a, b Note) int {
return compare(spec, spec.key(a), a.ID, spec.key(b), b.ID)
})
page := make([]Note, 0, q.limit+1)
for _, n := range all {
if q.pinned != nil && n.Pinned != *q.pinned {
continue
}
if q.after != nil && compare(spec, spec.key(n), n.ID, q.after.Key, q.after.ID) <= 0 {
continue
}
page = append(page, n)
if len(page) == q.limit+1 { // one extra row tells us a next page exists
break
}
}
if len(page) <= q.limit {
return page, ""
}
page = page[:q.limit]
last := page[len(page)-1]
return page, encodeCursor(cursor{Sort: q.sort, Key: spec.key(last), ID: last.ID})
}
type pageBody struct {
Items []Note `json:"items"`
Limit int `json:"limit"`
NextCursor string `json:"nextCursor,omitempty"`
}
func newRouter(st *MemoryStore) *gin.Engine {
r := gin.New()
r.GET("/notes", func(c *gin.Context) {
q, err := parseList(c.Request.URL.RawQuery)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
items, next := st.List(q)
c.JSON(http.StatusOK, pageBody{Items: items, Limit: q.limit, NextCursor: next})
})
return r
}
func at(min int) time.Time { return time.Date(2026, 3, 1, 9, min, 0, 0, time.UTC) }
func seed() *MemoryStore {
st := &MemoryStore{}
st.Add(Note{ID: "n1", Title: "Alpha", Pinned: true, CreatedAt: at(0)})
st.Add(Note{ID: "n2", Title: "Bravo", CreatedAt: at(5)})
st.Add(Note{ID: "n3", Title: "Charlie", CreatedAt: at(5)}) // same instant as n2
st.Add(Note{ID: "n4", Title: "Delta", Pinned: true, CreatedAt: at(10)})
st.Add(Note{ID: "n5", Title: "Echo", CreatedAt: at(15)})
return st
}
func get(r http.Handler, target string) (int, pageBody, string) {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, target, nil))
var p pageBody
_ = json.Unmarshal(w.Body.Bytes(), &p)
return w.Code, p, w.Body.String()
}
func ids(ns []Note) string {
out := make([]string, len(ns))
for i, n := range ns {
out[i] = n.ID
}
return "[" + strings.Join(out, " ") + "]"
}
func main() {
gin.SetMode(gin.TestMode)
// Offset pagination: a write between two page requests shifts every row.
st := seed()
q := listQuery{limit: 100, sort: "-created"}
all, _ := st.List(q)
page1 := all[0:2]
st.Add(Note{ID: "n6", Title: "Foxtrot", CreatedAt: at(20)})
all, _ = st.List(q)
fmt.Println("offset:", ids(page1), "then", ids(all[2:4]))
// Cursor pagination: the next page starts after the last key, not at a row count.
st = seed()
r := newRouter(st)
_, p, _ := get(r, "/notes?limit=2")
fmt.Println("cursor page 1:", ids(p.Items))
raw, _ := base64.RawURLEncoding.DecodeString(p.NextCursor)
fmt.Println("cursor decodes to", string(raw))
st.Add(Note{ID: "n6", Title: "Foxtrot", CreatedAt: at(20)})
for page := 2; p.NextCursor != ""; page++ {
_, p, _ = get(r, "/notes?limit=2&cursor="+p.NextCursor)
fmt.Printf("cursor page %d: %s more=%t\n", page, ids(p.Items), p.NextCursor != "")
}
_, p, _ = get(r, "/notes?pinned=true&sort=title")
fmt.Println("pinned by title:", ids(p.Items))
_, p, _ = get(r, "/notes?limit=500")
fmt.Println("limit=500 ->", p.Limit)
for _, target := range []string{"/notes?sort=password", "/notes?pined=true", "/notes?sort=title;DROP"} {
code, _, body := get(r, target)
fmt.Println(target, code, body)
}
}The offset line returns n5 and n4, then n4 again after n6 is inserted, the classic duplicate. The cursor walk returns n5 n4, then n3 n2, then n1 with more=false; the new n6 does not disturb later pages because it sorts before the cursor and will appear on a fresh first page. n2 and n3 share a timestamp, and the ID breaks the tie deterministically. The decoded cursor is just JSON with the sort, the last key and the last ID. pinned=true with sort=title returns n1 n4, limit=500 is clamped to 100 and echoed back, and the three bad queries each get a 400 naming the problem. The last one matters: URL.Query, and therefore c.Query, silently drops pairs containing a semicolon, while url.ParseQuery reports the error so the API can reject it.
A total order needs a tie-breaker
If two rows compare equal on the sort key, neither SQL nor slices.SortFunc promises their relative order, and it can differ between two executions of the same query. A page that ends between tied rows then gives the next request no exact place to resume, so a row is skipped or repeated. Appending a unique column, the ID, to every sort order makes the order total, and the cursor must carry both values. Support it with a composite index such as (created_at, id). Watch the key format too. The in-memory model compares keys as strings, so timestamps are formatted at fixed width in UTC. PostgreSQL stores timestamps with microsecond precision while Go keeps nanoseconds, so truncate to microseconds before writing; otherwise the key in the cursor never equals the stored value and the boundary comparison is subtly wrong.
Opaque cursors are encoded, not secret
Calling the cursor opaque is a contract with clients: they must pass it back unchanged and never build one, so you can change its format later. It is not a security property. base64url is an encoding, and the program decodes the cursor in one line. Treat a cursor like any other input: decode it, validate every field, reject it if it was issued for a different sort, and never place in it anything the caller could not already see. If tampering matters, append an HMAC computed with a server key and verify it before use. Authorization must not depend on the cursor; the owner filter comes from the authenticated request on every page, so a forged cursor can at most move the starting point within the caller's own notes. For the limit, pick a default, clamp at a maximum, echo the effective value and reject zero or non-numeric input with 400.
Allow-lists for filters and sorts, constants for SQL
Reject unknown query parameters: a client that types pined=true and silently receives every note has a bug that nobody will notice. For sorting, the allow-list is not just validation; it is the only bridge between user input and SQL text. A placeholder binds a value, never an identifier, so ORDER BY $1 sorts every row by the same constant and no error appears. Interpolating the column name instead is SQL injection. Map each public sort name to a constant clause and build the query from those constants plus placeholders.
// Public sort name -> constant SQL. Client input selects a key; it never becomes SQL text.
var orderBy = map[string]string{
"created": "created_at ASC, id ASC",
"-created": "created_at DESC, id DESC",
"title": "title ASC, id ASC",
}
var afterCursor = map[string]string{
"created": "(created_at, id) > ($2, $3)",
"-created": "(created_at, id) < ($2, $3)",
"title": "(title, id) > ($2, $3)",
}
// listSQL assumes q came from parseList, so q.sort is a key of orderBy.
func listSQL(ownerID string, q listQuery) (string, []any) {
query := "SELECT id, title, pinned, created_at FROM notes WHERE owner_id = $1"
args := []any{ownerID}
if q.after != nil {
query += " AND " + afterCursor[q.sort]
args = append(args, q.after.Key, q.after.ID)
}
if q.pinned != nil {
args = append(args, *q.pinned)
query += fmt.Sprintf(" AND pinned = $%d", len(args))
}
args = append(args, q.limit+1) // one extra row reveals whether a next page exists
query += fmt.Sprintf(" ORDER BY %s LIMIT $%d", orderBy[q.sort], len(args))
return query, args
}This fragment is the PostgreSQL side of the same API; run it against a database in your own environment. orderBy and afterCursor are the allow-list expressed as SQL constants, and parseList has already guaranteed that q.sort is one of their keys. Only placeholder numbers are formatted into the string; every client-supplied value, including the cursor key and ID, travels in args. The row comparison (created_at, id) < ($2, $3) matches the ORDER BY direction and can use the composite index. Text keys such as title compare with the column collation in SQL, which may differ from the byte order the in-memory model uses.
TAKE THIS WITH YOU
Page by the last (sort key, id) in a validated opaque cursor, cap the limit, reject unknown parameters, and map allow-listed sort names to constant SQL instead of interpolating them.
Check your understanding
Two notes share the same created_at value. Why must both the cursor and ORDER BY also include the note ID?
Go to the source
Progress stays in this browser. No account needed.