Allowlisted API filters and sorting in Laravel Go
Pinned baseline and scope
Reference Spatie's MIT-licensed spatie/laravel-query-builder 7.3.10 at dee20864308f99258e462ebcf9b6eec2a1aafbb8, specifically src/Concerns/FiltersQuery.php, src/Concerns/SortsQuery.php, src/Filters/FiltersExact.php, src/Filters/FiltersPartial.php, src/QueryBuilderRequest.php, and tests. Keep MIT attribution when adapting source. Laravel Go baseline: 56c7fd3691dc4ccb636119308d6fcf919e308518, module go.laravel.com.
Check get-recipe's current port catalog; if it lists a Go port, verify its compatibility and offer it as an alternative to inlining. This recipe covers only one endpoint's exact status filter, literal name substring, fixed sort aliases, and stable bounded pagination. It does not implement relationship includes, arbitrary filter operators, JSON paths, sparse fields, or all package input coercions, and it has not been exercised in your app.
Observable source behavior
String allowed filters default to partial matching; exact filters use equality or set membership for arrays. Filter and sort names are checked against allowlists. A leading minus requests descending sort and multiple sorts preserve order. Partial search escapes LIKE wildcard characters before binding. Reusing an Eloquent base builder preserves its existing constraints; a Go translation must preserve those ownership constraints too.
Inventory the real endpoint's filters, defaults, null/boolean/comma handling, error statuses, output resources, and includes before narrowing anything. Treat unsupported existing features as reasons to keep the package path or extend the declared scope, not to silently drop them.
Application-owned Go design
- Read query input at the handler boundary using the app's request conventions. Explicitly reject unknown filter keys and non-scalar values. Bound lengths, page size, and sort count. Optional struct fields are not permission to ignore malformed security-relevant filters.
- Build the base query with the authenticated tenant/owner condition first. Never accept tenant scope, table names, or SQL column identifiers from client input.
- Add fixed exact conditions for a validated status enum. For literal partial matching, binding alone does not escape SQL LIKE wildcards. A fixed-column fragment is
escaped := strings.NewReplacer("!", "!!", "%", "!%", "_", "!_").Replace(strings.ToLower(name)), thenquery.WhereRaw("LOWER(users.name) LIKE ? ESCAPE '!'", "%"+escaped+"%"). Importstrings; the column is a fixed app-owned identifier. The explicit!escape avoids driver-dependent backslash assumptions. Check Unicode lowercasing/collation on the actual deployed driver; Go and database case folding need not agree for every language. - Parse sort tokens using a fixed switch. The following is an integration fragment assuming
queryis an authorized*db.Queryand the aliases belong to your real table:
switch token {
case "name":
query = query.OrderBy("users.name")
case "-name":
query = query.OrderByDesc("users.name")
case "created_at":
query = query.OrderBy("users.created_at")
case "-created_at":
query = query.OrderByDesc("users.created_at")
default:
// Return the endpoint's documented validation error before executing SQL.
}
OrderBy and OrderByDesc are distinct methods at this revision; do not invent an OrderBy(column, direction) overload. Append OrderBy("users.id") for deterministic ties. The default branch must return, not fall through to execute a partially sorted query.
- Apply default sorting only if no sort was supplied. Use the existing pagination/response layer and an explicit resource shape; do not expose every model field. Reject unsupported
includeandfieldsrequests and retain base authorization regardless of filters. - Keep this as an endpoint-owned adapter rather than a generic query DSL. Every query must use the request/context-bound connection and existing transaction context where appropriate.
Trial and acceptance
Use two tenants and rows with duplicate names/timestamps, different statuses, and a literal name A_100%.
- Assert exact ordered IDs for
sort=-created_at,name, including stable page boundaries and exclusion of the other tenant. _100%matches the literal substring only; quotes/backslashes never alter SQL structure.- Unknown aliases, SQL-shaped sort tokens, arrays, invalid status values, unsupported includes, excessive lengths, and unbounded pages fail before execution.
- Missing, empty,
0, and boolean-like values behave as the documented contract says, not as incidental Go zero values dictate. - Compare status codes, visible fields, and pagination metadata against the PHP source-backed endpoint on the same fixtures.
Run gofmt, go test ./..., go test -race ./..., and go vet ./... in the target Laravel Go app, with integration coverage for its production database. Record Go/framework versions and deliberate compatibility differences with the change. Green tests elsewhere do not validate the target application's adaptation.