CodeGym /课程 /Go SELF /GET list:filters、sorting and stable output

GET list:filters、sorting and stable output

Go SELF
第 61 级, 课程 1
可用

1. Contract and response format

When you write a list endpoint, it feels like it is “just returning an array”. But list responses are exactly the kind of thing that start living their own lives: scripts parse them, automated tests are written against them, they are compared as JSON “for equality”, and users complain if items “jump” around. That is why the list contract is not only about the id/title/done fields, but also about ordering rules and filter behavior.

We fix the following contract for GET /api/v1/tasks:

  • Method and path: GET /api/v1/tasks
  • Query parameters:
    • done=true|false — optional status filter
    • sort=id|title — optional sorting
  • Response: 200 OK and a JSON object of the form { "tasks": [...] }, not a “bare array”, so the format can be extended without changing the response type (for example, by adding "total").

Why do we talk separately about “stability”? Because even seemingly “simple” things like sorting can produce different orders for equal elements when the implementation changes internally. This is one of the reasons why tests tied to ordering suddenly break.

To avoid turning clients into archaeologists, we make the output deterministic in advance.

DTO and response wrapper

Before filtering and sorting, it is important to agree on the form in which data leaves the system. In the HTTP layer we usually work with DTOs (data transfer objects) — structures that reflect the API contract and do not have to match the domain model 100% of the time. That is normal: the domain is about rules, HTTP is about packaging.

Minimal DTO and response wrapper:

type TaskDTO struct {
	ID    int    `json:"id"`
	Title string `json:"title"`
	Done  bool   `json:"done"`
}

type ListTasksResponse struct {
	Tasks []TaskDTO `json:"tasks"`
}

Why { "tasks": [...] }, and not just []TaskDTO? Because APIs rarely remain “just a list”. If you want to add total, next_page, generated_at — you will not have to make a painful format change where clients need to rewrite the parser from “array → object”.

And yes, this is one of those cases where an extra 10 bytes of JSON is a justified investment in peace of mind.

2. Query params: reading and processing

Query parameters look harmless because they are “just strings”. But in fact, they are just as much user input as a JSON body or {id} in the path: they can be empty, duplicated, unexpected, and all of that needs to be handled consistently. If we “accept everything as is”, the bugs will not appear immediately, but when a client accidentally sends ?done=tru and gets strange behavior.

In practice, r.URL.Query() returns url.Values, that is, map[string][]string.

import "net/http"

func readQuery(r *http.Request) map[string][]string {
	q := r.URL.Query()
	return q
}

And here comes the first subtlety: a single key can be passed multiple times, for example ?sort=id&sort=title. For learning purposes, we will choose a strict policy: if a parameter is specified more than once, it is a validation error (400), because otherwise it is hard for the client to predict the result.

Exactly one value for a parameter

Let us make a small helper to “take exactly one value”:

import (
	"fmt"
	"net/url"
)

func getSingleQuery(q url.Values, key string) (string, bool, error) {
	vals, ok := q[key]
	if !ok {
		return "", false, nil
	}
	if len(vals) != 1 {
		return "", true, fmt.Errorf("query %q must be single", key)
	}
	return vals[0], true, nil
}

Here present (the second result) is more important than it may seem. It helps distinguish between “the parameter is absent” and “the parameter is present, but empty/bad”. For done, this is critical.

done filter: three states instead of one bool

Filters have a classic beginner trap: you want to read done as a bool and stop there. But done in the query actually has three states, and they are semantically different:

  1. the parameter is absent → do not apply the filter
  2. the parameter is present and valid (true/false) → apply the filter
  3. the parameter is present but invalid → this is 400 (validation)

If you do not distinguish between (1) and (2), you get a bug: “parameter absent” will behave the same as done=false, and the client will suddenly see only incomplete tasks.

Let us write a parser for an optional bool:

import (
	"net/url"
	"strconv"
)

func parseOptionalBool(q url.Values, key string) (value bool, present bool, err error) {
	raw, present, err := getSingleQuery(q, key)
	if err != nil || !present {
		return false, present, err
	}
	if raw == "" {
		return false, true, strconv.ErrSyntax
	}
	v, err := strconv.ParseBool(raw)
	if err != nil {
		return false, true, err
	}
	return v, true, nil
}

Now to filtering. We want to do this as simply as possible and without extra allocations. The “in-place filtering” pattern looks like this: take dst := tasks[:0] and append matching elements. It sounds like magic, but in fact it is just careful reuse of the array under the slice.

func filterByDone(tasks []TaskDTO, done bool) []TaskDTO {
	dst := tasks[:0]
	for _, t := range tasks {
		if t.Done == done {
			dst = append(dst, t)
		}
	}
	return dst
}

If you are thinking now, “this looks like an ancient Go ritual” — that is normal. You will get used to it: in Go, these things are considered readable because they are short and predictable.

Query validation and converting errors to ValidationError

Inside the handler we do not want to spread around “if it fails here, write 400 like this, and elsewhere differently”. We already agreed that we have a single error path through writeError, which means the handler should return domain-friendly errors: ValidationError for 400 and ErrNotFound for 404 (though this is less often needed for list).

In this lecture we will assume that the ValidationError type and writeError/mapError already exist (you wrote them in the lecture about a unified error contract). Then query validation becomes a simple rule: anything invalid is &ValidationError{Fields: ...}.

For example, if done is invalid:

func invalidDoneQuery() error {
	return &ValidationError{
		Fields: map[string]string{
			"done": "must be true or false",
		},
	}
}

And if sort is unknown:

func invalidSortQuery() error {
	return &ValidationError{
		Fields: map[string]string{
			"sort": "supported: id, title",
		},
	}
}

This is convenient for the client: it always gets one format and can highlight the error next to a specific parameter. It is also convenient for you because the handler remains linear and readable.

3. Sorting and stable output

Sorting in a list endpoint is needed not only “for beauty”. It is needed for determinism: it is easier for the client (and your tests) to live when the same request always returns elements in the same order.

A key nuance: if you sort by a field that can be duplicated (for example, title) and do not define a secondary rule (tie-break), the order of elements with the same title may “wander”. Even with identical code, the order of equal elements may change between environments and tool versions.

We introduce the rules:

  • sort is absent or sort=id → sort by ID in ascending order
  • sort=title → sort by Title, and if Title values are equal, sort by ID

Code:

import (
	"fmt"
	"sort"
)

func sortTasks(tasks []TaskDTO, sortBy string) error {
	switch sortBy {
	case "", "id":
		sort.Slice(tasks, func(i, j int) bool { return tasks[i].ID < tasks[j].ID })
		return nil
	case "title":
		sort.Slice(tasks, func(i, j int) bool {
			if tasks[i].Title == tasks[j].Title {
				return tasks[i].ID < tasks[j].ID
			}
			return tasks[i].Title < tasks[j].Title
		})
		return nil
	default:
		return fmt.Errorf("unsupported sort: %s", sortBy)
	}
}

The tie-break by ID makes the result deterministic even when titles match. This is especially important if later you add tests that compare JSON “as a string” or golden files.

4. Handler: pipeline parse → list → filter → sort → encode

A list handler is great because it perfectly trains the “server-side sequence muscle”. We want the code to read top to bottom without jumping around the file.

Handler diagram:

flowchart TD
    A[GET /api/v1/tasks] --> B[parse query: done/sort]
    B --> C["app.List -> []TaskDTO"]
    C --> D[optional filter done]
    D --> E[sort + tie-break]
    E --> F["encode JSON {tasks:...}"]

Now the handler skeleton. We will keep the service layer minimal for now:

import "context"

type TaskLister interface {
	List(ctx context.Context) ([]TaskDTO, error)
}

And the handler itself:

import "net/http"

func (s *Server) handleListTasks(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()

	done, hasDone, err := parseOptionalBool(q, "done")
	if err != nil {
		writeError(w, &ValidationError{Fields: map[string]string{"done": "must be true or false"}})
		return
	}

	sortBy, _, err := getSingleQuery(q, "sort")
	if err != nil {
		writeError(w, &ValidationError{Fields: map[string]string{"sort": "must be single"}})
		return
	}

	tasks, err := s.app.List(r.Context())
	if err != nil {
		writeError(w, err)
		return
	}

	if hasDone {
		tasks = filterByDone(tasks, done)
	}
	if err := sortTasks(tasks, sortBy); err != nil {
		writeError(w, &ValidationError{Fields: map[string]string{"sort": "supported: id, title"}})
		return
	}

	writeJSON(w, http.StatusOK, ListTasksResponse{Tasks: tasks})
}

Pay attention to a few “small things that are not small”:

  • We always sort, even if sort is empty: that is stability by default.
  • We filter after receiving the data: this keeps parse/query logic out of the app layer. It is not the only possible design, but it is a good fit for learning: the HTTP layer is responsible for the “input/output contract”.
  • Query errors become ValidationError, and everything else is returned as the app layer decides (and then writeError will choose 400/404/500).

If you already have a writeJSON helper, it usually looks something like this:

import (
	"encoding/json"
	"net/http"
)

func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(status)
	_ = json.NewEncoder(w).Encode(v)
}

Request examples

Server code is only half the story. The other half is how people actually use it. When you look at an API through the client’s eyes, it becomes immediately obvious where the contract is leaky and where it is predictable.

Example 1: get all tasks, default sorting (by id)

curl -i "http://localhost:8080/api/v1/tasks"

Expected (example):

{
  "tasks": [
    { "id": 1, "title": "Buy milk", "done": false },
    { "id": 2, "title": "Write Go code", "done": true }
  ]
}

Example 2: completed only, sorted by title

curl -i "http://localhost:8080/api/v1/tasks?done=true&sort=title"

Example 3: query error

curl -i "http://localhost:8080/api/v1/tasks?done=tru"

And here it is especially important that the client gets not random text, but your unified error envelope, for example:

{
  "error": {
    "code": "validation",
    "message": "invalid request",
    "fields": {
      "done": "must be true or false"
    }
  }
}

Even if the client is written in another language, this format is trivial to process: code defines the class, fields makes it possible to highlight the exact location, and message is for the user.

5. Typical mistakes

Mistake #1: assuming that “if we do not sort, it will be in order anyway”.
While storage is in a slice and tasks are only appended to the end, it may seem that the order is “naturally stable”. But as soon as a map, file reading, merging from several sources, or simply an implementation change appears, the order becomes unpredictable. The right habit is: the list endpoint is responsible for the order itself and always sorts before returning data.

Mistake #2: forgetting that done has three states, and accidentally filtering by default.
If you do done, _ := strconv.ParseBool(q.Get("done")), then the absence of the parameter becomes false, and you suddenly return only incomplete tasks. The client will think that “the server is losing data”. There is only one way to fix it: return (value, present, err) and apply the filter only when present.

Mistake #3: sorting by title without a tie-break and being surprised by the “jumping” order.
When two title values are equal, sorting without a secondary criterion does not promise that the elements will remain “as before”. Between tool versions or with a different data set, the order of equal elements may change. To avoid phantom test failures, add a tie-break (for example, id).

Mistake #4: accepting ?sort=id&sort=title and silently “taking the first value”.
Such an API becomes inconvenient to debug: the client made a mistake, and the server silently did “something”. In stable contracts it is better either to clearly document the rule “take the first one” or, which is simpler for learning and more reliable, return 400 and require a single parameter.

Mistake #5: returning a bare array instead of an object and then “having nowhere to extend it”.
Today it seems to you that the task list is just []TaskDTO. Tomorrow you will need total, the day after tomorrow — a timestamp or a version. If the response is already an object {"tasks": [...]}, you can add a field without pain. If the response is an array, you will have to break the client parser. This is that rare case where a small amount of “redundancy” in JSON really saves weeks of life.

1
任务
Go SELF, 第 61 级, 课程 1
已锁定
单个参数
单个参数
1
任务
Go SELF, 第 61 级, 课程 1
已锁定
三态布尔
三态布尔
1
任务
Go SELF, 第 61 级, 课程 1
已锁定
过滤与排序
过滤与排序
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION