A REST API in Go: Planning, CRUD, Validation, Repository Pattern, DI, Pagination, Swagger
"If a handler function wants a dependency, it can bloody well ask for it as an argument. No more surprise dependencies when you’re just trying to test a single handler." — Mat Ryer, "How I write HTTP services in Go after 13 years", Grafana Labs blog, February 2024
Summary: One complete, production-shaped JSON API in plain Go: plan the resources and URLs first, then build handlers that decode bounded DTOs, validate them, call a service layer that owns a repository interface, and answer with consistent status codes and RFC 9457 Problem Details; add keyset pagination with a Link header, filtering and sorting, PATCH as JSON Merge Patch, ETag/If-Match against lost updates, an Idempotency-Key for POST, /v1 versioning, an OpenAPI 3.1 contract served with Scalar, end-to-end tests through httptest, and a run function that wires everything by constructor injection and shuts down gracefully. Focus: project planning, resource modelling, URL design, handlers and maker functions, DTOs, request validation (go-playground/validator vs hand-written Validate()), the error envelope, status codes, the repository pattern with one interface per aggregate, the service layer, dependency injection via constructors, the run function pattern (Mat Ryer), configuration via env, pagination (offset vs cursor/keyset), filtering, sorting, PATCH semantics, ETag and If-Match, idempotency keys, versioning, OpenAPI 3.1 and the code generators (swaggo/swag vs oapi-codegen vs ogen), generated clients, testing, graceful shutdown, health endpoints, structured logging, request IDs and a rate limiting hook. Learning goal: Design and ship a small REST service in Go whose every response, including every error, is predictable for a client and for a generated SDK; know which design choice protects against which production failure (duplicate charges, lost updates, page drift, leaked internals, spec drift, dropped requests on deploy); and be able to defend each choice against the Laravel defaults you may already know.
This page is the project chapter of the HTTP group: it assembles pieces that other chapters own and only explains them as far as the API needs. Routing patterns, ServeMux precedence and server timeouts are in net/http: Server, Client, 1.22 Routing; chaining, CORS, compression, the logging and recover middlewares and token-bucket rate limiters are in Middlewares and Rate Limiting in Go; the SQL side of a repository, pools and transactions are in database/sql & pgx; fakes, mocks and DI for tests in Mocking with Interfaces & DI; httptest and table tests in Testing & Benchmarking; struct tags and the JSON decoder in JSON, XML & Encoding; ctx threading in context; signals in OS Processes, Signals & Graceful Shutdown. The language-neutral design rules are in REST API Design, API Versioning, API Idempotency and Pagination; the DDD view of repositories and APIs in Repositories and API Realization: REST & GraphQL. Authentication is the next chapter, Authentication in Go.
Facts below were checked against RFC 9457 (Problem Details), RFC 9110 (HTTP Semantics), RFC 7396 (JSON Merge Patch), RFC 5789 (PATCH), RFC 6585 (428 and 429), RFC 8288 (Web Linking), RFC 6901 (JSON Pointer), the IETF drafts draft-ietf-httpapi-idempotency-key-header-09 and draft-ietf-httpapi-ratelimit-headers, the OpenAPI Specification 3.1.0, 3.1.1 and the latest 3.2.1, the Go 1.21 to 1.27 release notes and the Go 1.27 source of net/http, encoding/json and os/signal on go.dev, the READMEs of go-playground/validator, swaggo/swag (v1 and the v2 branch), oapi-codegen, ogen, kin-openapi, huma, Scalar and Swagger UI, the Go module proxy for every version number quoted, Mat Ryer's 2024 post, the go.dev Gin tutorial, Google's AIPs 122, 132, 134, 154, 158, 160, 185 and 193, Stripe's API reference (pagination, idempotency, errors, versioning), GitHub's REST docs (pagination, API versions), the JSON:API specification and its cursor-pagination profile, Kubernetes' probe documentation, Markus Winand's "No Offset" and the PostgreSQL manual, and the Laravel 13 documentation for API Resources, validation, pagination, routing and controllers. Snippets declare go 1.24.0 (they use t.Context() and slog.DiscardHandler from 1.24, range-over-func and Request.Pattern from 1.23, ServeMux method patterns from 1.22) and pin github.com/go-playground/validator/v10 v10.30.1, the last release whose go.mod still says go 1.24.0 (v10.30.2 moved to 1.25). They were compiled, vetted and tested with -race on Go 1.27.4 (macOS, Apple M4 Pro); the curl transcripts in the lab are from a real run of the binary.
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why an API needs more than "handlers that return JSON" | Why it exists |
| Fielding, RFC 7807 to 9457, Swagger to OpenAPI 3.1, Go 1.22 routing | Where it comes from |
| The first draft and the finished service side by side | Go |
| Project planning, resource modelling, URL design | Planning the API |
| Handlers, maker functions, the routes table | Handlers |
| Request and response types (DTOs) | DTOs |
| Request validation (go-playground/validator vs hand-written Validate()) | Validation |
| The error envelope, problem details RFC 9457 | Problem Details |
| Which status code for which outcome | Status codes |
| Repository pattern, interface per aggregate | Repository |
| Service layer | Service layer |
| Dependency injection via constructors, run function pattern (Mat Ryer) | DI and run |
| Configuration via env | Configuration |
| Pagination (offset vs cursor/keyset), Link header / next cursor | Pagination |
| Filtering, sorting | Filtering and sorting |
| Partial updates PATCH, JSON Merge Patch | PATCH |
| ETag and If-Match, 412 and 428 | Optimistic concurrency |
| Idempotency key for POST | Idempotency-Key |
| Versioning (/v1) | Versioning |
| OpenAPI 3.1 contract and a drift test | OpenAPI |
| swaggo/swag vs oapi-codegen vs ogen, generated clients | Generators |
| API documentation serving (Swagger UI / Scalar) | Serving docs |
| httptest end-to-end tests, in-memory repository for tests | Testing |
| Graceful shutdown, health endpoints | Shutdown and health |
| Structured logging, request IDs, rate limiting hook | Observability hooks |
| Decoder internals, 405 handling, keyset SQL, exact error bodies | Mechanics |
| The classic API bugs and their fixes | Solving the classic problems |
| What to use when | Choosing |
| Monolith to distributed system | In architecture |
| Run it on your machine | Lab |
| Laravel API Resources comparison, FormRequest, apiResource | For PHP/Laravel developers |
Everything in one minute
The API surface. Six operations on one collection, plus three infrastructure routes. Every row is unpacked in the concept catalogue.
| Method and path | Purpose | Success | Typical errors | Idempotent (RFC 9110) |
|---|---|---|---|---|
GET /v1/products | List, filter, sort, paginate | 200 + Link: rel="next" | 400 bad query or cursor | Yes (safe) |
POST /v1/products | Create | 201 + Location + ETag | 400, 409 duplicate SKU, 413, 415, 422 | No: use Idempotency-Key |
GET /v1/products/{id} | Read one | 200 + ETag, or 304 | 404 | Yes (safe) |
PUT /v1/products/{id} | Replace the writable fields | 200 + new ETag | 412, 422, 428 | Yes |
PATCH /v1/products/{id} | Merge-patch some fields | 200 + new ETag | 400, 412, 415, 422, 428 | No (by definition), safe with If-Match |
DELETE /v1/products/{id} | Delete | 204 | 404, 412, 428 | Yes |
GET /healthz, GET /readyz | Liveness, readiness | 200 / 503 | Yes | |
GET /openapi.json, GET /docs | Contract and reference page | 200 | Yes |
The layers. Each has one job and depends only on the layer below it.
| Layer | Package in the snippets | Knows about | Never knows about |
|---|---|---|---|
| Composition root | app (Run), cmd/api | Every concrete type, env, flags, signals | Business rules |
| HTTP adapter | httpapi, dto, problem | Status codes, headers, JSON, DTOs | SQL |
| Service (use cases) | service | Domain types, the Repository interface it owns | HTTP, SQL |
| Domain | product | Invariants, domain errors | Everything else |
| Persistence | memrepo, pgrepo | Storage | HTTP |
The headers that carry the protocol.
| Header | Direction | Job | Defined by |
|---|---|---|---|
Content-Type: application/problem+json | Response | Marks an error body | RFC 9457 |
Location | Response to POST | URL of the created resource | RFC 9110 |
ETag / If-Match / If-None-Match | Both | Version of a representation; conditional writes and reads | RFC 9110 |
Link: <…>; rel="next" | Response | URL of the next page | RFC 8288 |
Idempotency-Key | Request | Makes a POST safe to retry | IETF draft (Stripe has used it for years) |
Retry-After | Response to 429/503 | When to try again | RFC 9110, RFC 6585 |
X-Request-ID | Both | Correlate client, gateway and server logs | Convention (no RFC) |
Why it exists
net/http makes the first endpoint take ten lines, and that is the trap: the first draft of almost every Go API returns JSON from handlers that read the body without a limit, ignore unknown fields, report validation failures as 200 {"error": "..."}, page with OFFSET, overwrite rows blindly on PUT and keep the data in a package-level map. It works in a demo. In production each shortcut becomes a specific incident: a client SDK that cannot tell success from failure, a mobile app that shows the same item twice while scrolling, two admins whose edits silently erase each other, a payment created twice because the client retried after a timeout, a stack trace in an error message, a deploy that drops in-flight requests.
A REST API is a contract with clients you do not control. The work in this chapter is mostly about making that contract explicit (resources, URLs, representations, status codes, error bodies, headers, an OpenAPI document) and then making the Go code structurally unable to break it (DTOs separate from domain types, one error-mapping function, a contract test against the spec, end-to-end tests through the real handler stack).
| Ad-hoc handlers | A designed API |
|---|---|
Status 200 with {"error": ...} | Real status codes and RFC 9457 bodies |
json.Decode into the domain struct | A DTO per operation, bounded body, unknown fields rejected |
OFFSET + COUNT(*) | Keyset cursor, Link header, no total by default |
| Last write wins | ETag + If-Match, 412 on conflict |
| Retried POST creates a duplicate | Idempotency-Key replays the first response |
| Docs written once, wrong by the next sprint | OpenAPI contract checked by a test |
Globals and init() | Constructors and one run function |
| Fewer files on day one | More types and files; each one obvious |
An everyday picture. A good restaurant's order desk. The menu is the contract (OpenAPI): it names the dishes (resources) and what you may ask for. The order slip has fixed boxes (a DTO); the clerk checks it before it reaches the kitchen (validation) and hands back a printed reason if something is wrong (Problem Details), not a shrug. The kitchen (service layer) does not care whether the order came by phone or by app. Each order gets a number (Idempotency-Key): if you phone twice about the same order, you get the same order, not two meals. The pantry (repository) can be a fridge in a test kitchen or a cold store in production. When the restaurant closes, the door is locked first and the orders already being cooked are finished (graceful shutdown).
Three common misunderstandings, up front
- "REST means CRUD over my tables." Fielding's resources are concepts clients care about ("Any information that can be named can be a resource"), not rows. A
POST /v1/orders/{id}/cancellationis fine REST; aPATCHthat lets a client setstatusto anything is a leak of your table into your contract. - "Validation is the framework's job." Go has no framework doing it for you, and that is an advantage: decoding, shape validation and business rules are three different steps with three different failure codes (400, 422, 409), and you write each explicitly.
- "Swagger generates the docs, so the docs are correct." Annotations and the code drift apart unless something fails when they do. Either generate code from the spec, generate the spec from code, or test the routes against the spec, as this chapter does.
Where it comes from
Roy Fielding named REST in his 2000 dissertation at UC Irvine, "Architectural Styles and the Design of Network-based Software Architectures". Chapter 5 defines the uniform interface through four constraints: "identification of resources; manipulation of resources through representations; self-descriptive messages; and, hypermedia as the engine of application state", and the resource as "a conceptual mapping to a set of entities, not the entity that corresponds to the mapping at any particular point in time". Most JSON APIs called REST today follow the first three and use links sparingly (a Link header for the next page, a Location after create).
The HTTP pieces came one RFC at a time. PATCH was added by RFC 5789 (March 2010), JSON Merge Patch by RFC 7396 (October 2014), Link headers by RFC 5988 and its successor RFC 8288 (October 2017). RFC 6585 (April 2012) added 428 Precondition Required and 429 Too Many Requests. RFC 7807 (March 2016) defined Problem Details; RFC 9457 (July 2023) "obsoletes RFC 7807", adds a registry of problem types and the guidance on multiple problems. RFC 9110 (June 2022) consolidated HTTP semantics and renamed 422 "Unprocessable Content" (Go's http.StatusText(422) still says "Unprocessable Entity"). The Idempotency-Key header, used by Stripe for years, is being standardised as draft-ietf-httpapi-idempotency-key-header (draft 09 is current, still an Internet-Draft).
The contract side started as the Swagger Specification (1.0 on 2011-08-10, 2.0 on 2014-09-08); Swagger 2.0 was donated to the OpenAPI Initiative on 2015-12-31 and continued as the OpenAPI Specification. OpenAPI 3.1.0 was released on 2021-02-15 and is the first version whose Schema Object "is a superset of JSON Schema Specification Draft 2020-12" and which adds webhooks. 3.1.1 is a patch release; 3.2.x is the latest line (3.2.1 at the time of writing). In Go, swaggo/swag generates Swagger 2.0 from comments; oapi-codegen and ogen generate Go from OpenAPI 3.
On the Go side, Go 1.22 (released 6 February 2024) added methods and wildcards to ServeMux patterns ("Wildcards in patterns, like /items/{id}, match segments of the URL path. The actual segment value may be accessed by calling the Request.PathValue method"), which removed the main reason to pick a third-party router for a JSON API. Go 1.23 added Request.Pattern and range-over-func iterators; Go 1.24 added omitzero, t.Context() and slog.DiscardHandler; Go 1.27 made encoding/json/v2 a regular package and re-implemented encoding/json on top of it ("the exact text of error messages may differ"). Mat Ryer's "How I write HTTP services in Go after 13 years" (February 2024) is the most quoted description of the structure this chapter uses: NewServer, routes.go, func main() that only calls run(), maker functions, generic encode/decode, and end-to-end tests that call run.
Go
Before
The first draft: one handler switching on the method, a global map, errors as 200, an unbounded body decoded straight into the stored struct (unknown fields ignored, the decode error dropped), page numbers with a total, and a PUT that overwrites whatever is there. Each test documents one way it misleads a client.
// Package before is a first-draft products API that works in a demo: global
// state, one function per verb, errors as 200 + {"error": "..."}, offset
// pagination with a COUNT, blind updates and validation mixed into handlers.
package before
import (
"encoding/json"
"net/http"
"sort"
"strconv"
"sync"
)
type Product struct {
ID int `json:"id"`
SKU string `json:"sku"`
Name string `json:"name"`
Price int `json:"price"`
}
var (
mu sync.Mutex
db = map[int]*Product{} // global: every test shares it
nextID = 1
)
// Reset exists only because the state is global.
func Reset() {
mu.Lock()
defer mu.Unlock()
db, nextID = map[int]*Product{}, 1
}
func Routes(mux *http.ServeMux) {
mux.HandleFunc("/products", products) // one handler switches on the method
}
func products(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
size, _ := strconv.Atoi(r.URL.Query().Get("size")) // no maximum
if size == 0 {
size = 10
}
mu.Lock()
all := make([]*Product, 0, len(db))
for _, p := range db {
all = append(all, p)
}
mu.Unlock()
sort.Slice(all, func(i, j int) bool { return all[i].ID > all[j].ID })
from := page * size
if from > len(all) {
from = len(all)
}
to := min(from+size, len(all))
json.NewEncoder(w).Encode(map[string]any{"items": all[from:to], "total": len(all)})
case http.MethodPost:
var p Product
json.NewDecoder(r.Body).Decode(&p) // unbounded body, unknown fields ignored, error dropped
if p.SKU == "" {
json.NewEncoder(w).Encode(map[string]string{"error": "sku required"}) // 200 OK
return
}
mu.Lock()
p.ID = nextID
nextID++
db[p.ID] = &p
mu.Unlock()
json.NewEncoder(w).Encode(p) // 200, no Location
case http.MethodPut:
var p Product
json.NewDecoder(r.Body).Decode(&p)
mu.Lock()
db[p.ID] = &p // last write wins, creates the row if it did not exist
mu.Unlock()
json.NewEncoder(w).Encode(p)
default:
w.Write([]byte("unsupported"))
}
}package before
import (
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func call(t *testing.T, method, target, body string) *httptest.ResponseRecorder {
t.Helper()
mux := http.NewServeMux()
Routes(mux)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(method, target, strings.NewReader(body)))
return rec
}
// The draft "works", but its failure modes are invisible to HTTP clients.
func TestTheDraftHidesFailures(t *testing.T) {
Reset()
if rec := call(t, "POST", "/products", `{"name":"no sku"}`); rec.Code != 200 {
t.Fatalf("validation failure reported as %d", rec.Code)
}
if rec := call(t, "POST", "/products", `{"sku":"A","colour":"red","price":"9"}`); rec.Code != 200 {
t.Fatalf("bad body reported as %d", rec.Code)
}
if rec := call(t, "DELETE", "/products", ""); rec.Code != 200 {
t.Fatalf("unsupported method reported as %d", rec.Code)
}
}
// Two clients edit the same product; the second silently erases the first.
func TestLostUpdate(t *testing.T) {
Reset()
call(t, "POST", "/products", `{"sku":"MUG","name":"Mug","price":900}`)
call(t, "PUT", "/products", `{"id":1,"sku":"MUG","name":"Mug","price":1200}`) // client A: new price
call(t, "PUT", "/products", `{"id":1,"sku":"MUG","name":"Coffee mug","price":900}`) // client B: new name, stale price
var page struct{ Items []Product }
_ = json.NewDecoder(call(t, "GET", "/products", "").Body).Decode(&page)
if page.Items[0].Price != 900 {
t.Fatalf("expected A's price change to be lost, got %+v", page.Items[0])
}
}
// Offset paging skips or repeats rows when the list changes between pages.
func TestOffsetPagingRepeatsRows(t *testing.T) {
Reset()
for range 4 {
call(t, "POST", "/products", `{"sku":"X"}`)
}
var p1, p2 struct{ Items []Product }
_ = json.NewDecoder(call(t, "GET", "/products?page=0&size=2", "").Body).Decode(&p1) // ids 4 3
call(t, "POST", "/products", `{"sku":"NEW"}`) // id 5 at the head
_ = json.NewDecoder(call(t, "GET", "/products?page=1&size=2", "").Body).Decode(&p2) // ids 3 2
if p1.Items[1].ID != p2.Items[0].ID {
t.Fatalf("expected id %d twice, pages %v / %v", p1.Items[1].ID, p1.Items, p2.Items)
}
}After
The finished service is split into packages, each shown in its concept block. Here are the two ends of it. NewServer builds the API as one http.Handler: a routes table that is the whole API surface, then the middleware that applies to all routes.
// Package httpapi is the HTTP adapter: routes, handlers, DTO decoding,
// Problem Details, ETags, pagination links and the middleware stack. It
// depends on the service layer, never the other way round.
package httpapi
import (
"context"
"log/slog"
"net/http"
"time"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/openapi"
"academy/rest-api-project/pagination"
"academy/rest-api-project/service"
)
// Limiter is the rate limiting hook: nil means no limit. Plug in a token
// bucket (golang.org/x/time/rate) keyed by API key or client IP.
type Limiter interface {
Allow(r *http.Request) (ok bool, retryAfter time.Duration)
}
// Deps lists every dependency of the HTTP layer. Mat Ryer's NewServer takes
// them as plain arguments; a struct is the same idea once the list grows.
type Deps struct {
Logger *slog.Logger
Products *service.Service
Cursors pagination.Codec
Idempotency *idempotency.Store
RequireIdemKey bool
Limiter Limiter
Ready func(context.Context) error
MaxBodyBytes int64
}
// NewServer builds the whole API as one http.Handler: the mux with every
// route, then the middleware that applies to all of them, outermost last.
func NewServer(d Deps) http.Handler {
mux := http.NewServeMux()
for _, rt := range routes(d) {
mux.Handle(rt.pattern, rt.handler)
}
var h http.Handler = problemFallback(mux)
h = rateLimit(d.Limiter, h)
h = logRequests(d.Logger, h)
h = recoverPanics(d.Logger, h)
h = requestID(h)
return h
}
type route struct {
pattern string
handler http.Handler
documented bool // part of the public contract in openapi.json
}
// routes is the entire API surface in one table: read it to know the API.
func routes(d Deps) []route {
idem := d.Idempotency.Middleware(d.RequireIdemKey, d.MaxBodyBytes)
return []route{
{"GET /v1/products", handleList(d.Products, d.Cursors), true},
{"POST /v1/products", idem(handleCreate(d.Products, d.MaxBodyBytes)), true},
{"GET /v1/products/{id}", handleGet(d.Products), true},
{"PUT /v1/products/{id}", handleReplace(d.Products, d.MaxBodyBytes), true},
{"PATCH /v1/products/{id}", handlePatch(d.Products, d.MaxBodyBytes), true},
{"DELETE /v1/products/{id}", handleDelete(d.Products), true},
{"GET /healthz", handleHealthz(), false},
{"GET /readyz", handleReadyz(d.Ready), false},
{"GET /openapi.json", openapi.SpecHandler(), false},
{"GET /docs", openapi.DocsHandler("/openapi.json"), false},
}
}
// Routes returns the documented "METHOD /path" patterns, for the contract test.
func Routes() []string {
var out []string
for _, rt := range routes(Deps{Idempotency: idempotency.NewStore(0, time.Now)}) {
if rt.documented {
out = append(out, rt.pattern)
}
}
return out
}And Run, the program as a function: main only calls it, and the end-to-end test calls it too.
// Package app holds Run, the whole program as a function: main only calls
// it, tests call it too (Mat Ryer's run function pattern).
package app
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"flag"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"sync/atomic"
"syscall"
"time"
"academy/rest-api-project/config"
"academy/rest-api-project/httpapi"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/pagination"
"academy/rest-api-project/service"
)
// Run takes the operating system as arguments and returns an error instead
// of calling os.Exit, so a test can start the real program in a goroutine.
func Run(ctx context.Context, args []string, getenv func(string) string, stdout io.Writer) error {
ctx, cancel := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
defer cancel()
cfg, err := config.Load(getenv)
if err != nil {
return fmt.Errorf("config: %w", err)
}
fs := flag.NewFlagSet(args[0], flag.ContinueOnError)
fs.StringVar(&cfg.Addr, "addr", cfg.Addr, "listen address (overrides API_ADDR)")
if err := fs.Parse(args[1:]); err != nil {
return err
}
log := slog.New(slog.NewJSONHandler(stdout, &slog.HandlerOptions{Level: cfg.LogLevel}))
// Composition root: the only place that knows every concrete type.
// Both repositories satisfy this type, so swapping in pgrepo.New(db) (with a
// *sql.DB opened through a registered driver) is a one-line change.
var repo interface {
service.Repository
Ping(context.Context) error
} = memrepo.New()
svc := service.New(repo, time.Now, newID)
var draining atomic.Bool
handler := httpapi.NewServer(httpapi.Deps{
Logger: log,
Products: svc,
Cursors: pagination.Codec{Key: cfg.CursorKey},
Idempotency: idempotency.NewStore(24*time.Hour, time.Now),
RequireIdemKey: cfg.RequireIdemKey,
MaxBodyBytes: cfg.MaxBodyBytes,
Ready: func(ctx context.Context) error {
if draining.Load() {
return errors.New("shutting down")
}
return repo.Ping(ctx)
},
})
ln, err := net.Listen("tcp", cfg.Addr)
if err != nil {
return err
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
ErrorLog: slog.NewLogLogger(log.Handler(), slog.LevelWarn),
}
serveErr := make(chan error, 1)
go func() { serveErr <- srv.Serve(ln) }()
log.Info("listening", "addr", ln.Addr().String())
select {
case err := <-serveErr:
return err
case <-ctx.Done():
}
// Graceful shutdown: fail readiness first and give the load balancer
// DrainDelay to notice, then stop accepting and wait for in-flight
// requests, bounded by the shutdown timeout.
draining.Store(true)
log.Info("shutting down", "drain_delay", cfg.DrainDelay.String(), "timeout", cfg.ShutdownTimeout.String())
time.Sleep(cfg.DrainDelay)
sctx, scancel := context.WithTimeout(context.WithoutCancel(ctx), cfg.ShutdownTimeout)
defer scancel()
if err := srv.Shutdown(sctx); err != nil {
return fmt.Errorf("shutdown: %w", err)
}
if err := <-serveErr; !errors.Is(err, http.ErrServerClosed) {
return err
}
log.Info("stopped")
return nil
}
func newID() string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return "prd_" + hex.EncodeToString(b)
}// Command api runs the products API. All the work is in app.Run.
package main
import (
"context"
"fmt"
"os"
"academy/rest-api-project/app"
)
func main() {
if err := app.Run(context.Background(), os.Args, os.Getenv, os.Stdout); err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}The Go angle
Go gives you a production-grade HTTP server, router, JSON codec, structured logger and test server in the standard library and no framework conventions on top. That is why Go APIs either look like the "Before" file or like a small, explicit version of what Laravel or Spring do for you: you write the DTOs, the error mapping and the wiring yourself, and in exchange every behaviour is visible in code you can read and test. The ecosystem fills specific gaps rather than the whole stack: go-playground/validator for tag validation (Gin's default validator), oapi-codegen and ogen for spec-first code, swaggo/swag for comment-first Swagger, pgx for PostgreSQL, golang.org/x/time/rate for limits. The go.dev tutorial "Developing a RESTful API with Go and Gin" is the useful contrast: it serves /albums from an in-memory slice with Gin's router and says itself that "storing data in memory means that the set of albums will be lost each" time the server stops; it has no DTO split, no error envelope, no pagination and no tests, because its goal is the first endpoint, not the hundredth. Frameworks such as Gin, Echo, Chi and huma exist and are fine; the patterns on this page apply to all of them, because they all end in an http.Handler.
The concept catalogue
Project planning, resource modelling and URL design Must-know
In plain words: Before writing a handler, write down what the client sees: which nouns exist (resources), which collections hold them, what each URL looks like, which fields a client may write and which it only reads, and which status codes each operation can return. That one page is the plan; the code, the OpenAPI document and the tests all follow it.
Common misunderstanding: "Resource modelling means one endpoint per table." A resource is what a client reasons about. A products table with an archived_at column can be one resource; an order and its lines are one aggregate with one URL for the order; a state change with side effects ("cancel this order, refund, notify") is often better as its own resource (POST /v1/orders/{id}/cancellation) than as a PATCH of a status field. Google's AIP-122 uses the same idea: resource names are paths of collection IDs and resource IDs, such as publishers/123/books/les-miserables.
Definition: project planning for an HTTP API produces four artefacts: a resource model (nouns, their fields, which are read-only, their lifecycle), a URL design (plural collection names, stable opaque IDs, nesting only for true ownership, a major version prefix), an operation table (method, path, request DTO, response DTO, status codes, headers, idempotency) and non-functional rules (page size limits, body size limit, timeouts, rate limits, auth). In this chapter the plan is the "API surface" table in one minute plus openapi.json.
1 Nouns product (sku, name, price_cents, currency, status, tags)
2 Read-only id, version, created_at, updated_at
3 Lifecycle draft -> active -> archived (archived is frozen)
4 URLs /v1/products collection
/v1/products/{id} item (id is opaque: prd_9b6b2a44e8ef67ef)
5 Operations GET list · POST create · GET · PUT · PATCH · DELETE
6 Rules limit <= 100, body <= 1 MiB, If-Match on writes, Idempotency-Key on POST
7 Contract openapi.json written from 1-6, then code, then tests against bothReal scenario: a catalogue service where marketing wants GET /products?category=shoes and the warehouse wants GET /products/{sku}; a booking API where "confirm" and "cancel" are actions with rules, not field edits; a multi-tenant SaaS that puts the tenant in the token, not in the path, so it cannot be forged; a public API where IDs must not be guessable integers.
| URL design rule | Good | Avoid | Why |
|---|---|---|---|
| Plural nouns for collections | /v1/products | /v1/getProducts, /v1/product | The method is the verb |
| Opaque, stable IDs | prd_9b6b2a44e8ef67ef | /products/17 | Not enumerable, survives a database move |
| Nest only for ownership | /v1/orders/{id}/lines | /v1/customers/{c}/orders/{o}/lines/{l}/notes | Deep paths duplicate keys and resist change |
| Actions as sub-resources | POST /v1/orders/{id}/cancellation | PATCH {"status":"cancelled"} with side effects | Rules and audit live in one place |
| Query string for views | ?status=active&sort=-price | /v1/products/active/by-price | Filters combine; paths do not |
| Major version in the path | /v1/... | /v1.3/... | Google AIP-185: "Google APIs use v1, not v1.0, v1.1, or v1.4.2" |
| snake_case or camelCase, once | price_cents everywhere | Mixed | Generated clients map names 1:1 |
Fix / how to use it: write the operation table and the OpenAPI document first; this chapter's contract test then keeps the routes and the document identical. Language-neutral URL rules are in REST API Design.
Handlers, maker functions and the routes table Must-know
In plain words: A handler turns one HTTP request into one response and nothing more: read the path and body, call the service, write the answer. Each handler is built by a function that receives its dependencies (handleCreate(svc, maxBytes)), and all routes are registered in one table, so reading one function tells you the whole API.
Common misunderstanding: "Handlers should be methods on a big server struct." That was Mat Ryer's earlier advice too; he changed it: "My handlers used to be methods hanging off a server struct, but I no longer do this." A method on a struct can use any field, so its real dependencies are invisible and every test must build the whole struct. A maker function's parameter list is its dependency list.
Definition: a maker function returns http.Handler (Mat Ryer: "My handler functions don’t implement http.Handler or http.HandlerFunc directly, they return them"); the closure can hold per-handler setup. Routes use Go 1.22 patterns "METHOD /path/{wildcard}", read with r.PathValue("id"); a path that matches with another method gets 405 with an Allow header from ServeMux itself. The chapter's routes(d Deps) []route is the equivalent of Mat Ryer's routes.go: the "entire API surface" in one place.
1 NewServer(deps)
2 for each route in routes(deps): mux.Handle("POST /v1/products", idem(handleCreate(svc, max)))
3 wrap: problemFallback(mux) -> rateLimit -> logRequests -> recoverPanics -> requestID
4 request POST /v1/products
5 requestID -> recover -> log -> rateLimit -> mux finds pattern -> idempotency -> handleCreate
6 handleCreate: decode[ProductWrite] -> svc.Create -> encode 201Real scenario: a new developer asked "which endpoints need auth?" reads one table; a handler test passes exactly the fakes the maker takes; adding GET /v1/products/{id}/history is one row plus one maker; a code reviewer sees that a handler takes *sql.DB and knows the layering was skipped.
| Style | Dependencies visible | Testable alone | Where it fits |
|---|---|---|---|
Maker function returning http.Handler | Yes, as parameters | Yes | This chapter, Mat Ryer |
| Method on a server struct | No, any field | Needs the whole struct | Older style, many tutorials |
Generated ServerInterface method (oapi-codegen) | Struct fields again | Yes, with a fake struct | Spec-first projects |
Framework handler (func(c *gin.Context)) | Via closure or struct | Through the framework's test kit | Gin, Echo |
Fix / how to use it: the handlers file below is the whole HTTP behaviour of the products resource; each function is linear: parse, call, map errors in one place (writeError), encode.
package httpapi
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"academy/rest-api-project/dto"
"academy/rest-api-project/mergepatch"
"academy/rest-api-project/pagination"
"academy/rest-api-project/problem"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// Maker functions return the handler; dependencies are their arguments.
func handleCreate(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
in, prob := decode[dto.ProductWrite](w, r, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
p, err := svc.Create(r.Context(), in.Draft())
if err != nil {
writeError(w, r, err)
return
}
w.Header().Set("Location", "/v1/products/"+p.ID)
w.Header().Set("ETag", etag(p.Version))
encode(w, http.StatusCreated, dto.View(p))
})
}
func handleGet(svc *service.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
p, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
tag := etag(p.Version)
w.Header().Set("ETag", tag)
if inm := r.Header.Get("If-None-Match"); inm != "" && parseCondition(inm).weakMatch(tag) {
w.WriteHeader(http.StatusNotModified)
return
}
encode(w, http.StatusOK, dto.View(p))
})
}
// handleReplace is PUT: the body is the complete new representation.
func handleReplace(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
in, prob := decode[dto.ProductWrite](w, r, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
cur, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
saveAndRespond(w, r, svc, cur.Version, in)
})
}
// handlePatch is RFC 7396 JSON Merge Patch: apply the patch to the current
// writable representation, then decode and validate the result like a PUT.
func handlePatch(svc *service.Service, maxBytes int64) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
if prob := requireMediaType(r, mergepatch.MediaType); prob != nil {
problem.Write(w, r, prob)
return
}
patch, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBytes))
if err != nil {
problem.Write(w, r, decodeProblem(err))
return
}
cur, err := svc.Get(r.Context(), r.PathValue("id"))
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
doc, _ := json.Marshal(dto.WriteOf(cur))
merged, err := mergepatch.ApplyJSON(doc, patch)
if err != nil {
problem.Write(w, r, problem.New(http.StatusBadRequest, "malformed-body", "Malformed merge patch", err.Error()))
return
}
// Re-run the normal decoder on the merged document: unknown or
// read-only members ("id", "version") are rejected here.
r2 := r.Clone(r.Context())
r2.Header.Set("Content-Type", "application/json")
r2.Body = io.NopCloser(strings.NewReader(string(merged)))
in, prob := decode[dto.ProductWrite](w, r2, maxBytes, "application/json")
if prob != nil {
problem.Write(w, r, prob)
return
}
saveAndRespond(w, r, svc, cur.Version, in)
})
}
// saveAndRespond writes with the version the precondition matched; the
// repository re-checks it atomically, so a concurrent writer still gets 412.
func saveAndRespond(w http.ResponseWriter, r *http.Request, svc *service.Service, version int64, in dto.ProductWrite) {
p, err := svc.Replace(r.Context(), r.PathValue("id"), version, in.Draft())
if err != nil {
writeError(w, r, err)
return
}
w.Header().Set("ETag", etag(p.Version))
encode(w, http.StatusOK, dto.View(p))
}
func handleDelete(svc *service.Service) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cond, prob := requireIfMatch(r)
if prob != nil {
problem.Write(w, r, prob)
return
}
id := r.PathValue("id")
cur, err := svc.Get(r.Context(), id)
if err != nil {
writeError(w, r, err)
return
}
if !cond.strongMatch(etag(cur.Version)) {
problem.Write(w, r, staleProblem())
return
}
if err := svc.Delete(r.Context(), id, cur.Version); err != nil {
writeError(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
})
}
// handleList: filtering (status, min_price, max_price), sorting (sort=-price)
// and keyset pagination (limit, cursor) with a Link: rel="next" header.
func handleList(svc *service.Service, cursors pagination.Codec) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
q, fingerprint, prob := parseList(r.URL.Query(), cursors)
if prob != nil {
problem.Write(w, r, prob)
return
}
page, err := svc.List(r.Context(), q)
if err != nil {
writeError(w, r, err)
return
}
out := dto.ListView{Data: make([]dto.ProductView, 0, len(page.Items))}
for _, p := range page.Items {
out.Data = append(out.Data, dto.View(p))
}
if page.Next != nil {
out.NextCursor = cursors.Encode(fingerprint, *page.Next)
out.HasMore = true
next := *r.URL
v := next.Query()
v.Set("cursor", out.NextCursor)
next.RawQuery = v.Encode()
w.Header().Set("Link", "<"+next.RequestURI()+`>; rel="next"`)
}
encode(w, http.StatusOK, out)
})
}
func parseList(v url.Values, cursors pagination.Codec) (product.ListQuery, string, *problem.Problem) {
bad := func(param, detail string) *problem.Problem {
return problem.New(http.StatusBadRequest, "invalid-query", "Invalid query parameter", param+": "+detail)
}
var q product.ListQuery
n := 0
if s := v.Get("limit"); s != "" {
var err error
if n, err = strconv.Atoi(s); err != nil {
return q, "", bad("limit", "must be an integer")
}
}
limit, ok := pagination.ClampLimit(n)
if !ok {
return q, "", bad("limit", "must not be negative")
}
q.Limit = limit
if s := v.Get("status"); s != "" {
if !product.Status(s).Valid() {
return q, "", bad("status", "must be draft, active or archived")
}
q.Status = product.Status(s)
}
for _, f := range []struct {
name string
dst **int64
}{{"min_price", &q.MinPrice}, {"max_price", &q.MaxPrice}} {
if s := v.Get(f.name); s != "" {
n, err := strconv.ParseInt(s, 10, 64)
if err != nil || n < 0 {
return q, "", bad(f.name, "must be a non-negative integer (cents)")
}
*f.dst = &n
}
}
sort := v.Get("sort")
if sort == "" {
sort = "-created_at"
}
field, desc := strings.CutPrefix(sort, "-")
switch product.SortField(field) {
case product.SortCreatedAt, product.SortPrice, product.SortName:
q.Sort, q.Desc = product.SortField(field), desc
default:
return q, "", bad("sort", "must be one of created_at, price, name, optionally prefixed with -")
}
// The cursor is only valid for the same filter and sort it was made for.
fp := url.Values{"status": {v.Get("status")}, "min_price": {v.Get("min_price")},
"max_price": {v.Get("max_price")}, "sort": {sort}}.Encode()
if s := v.Get("cursor"); s != "" {
c, err := cursors.Decode(fp, s)
if err != nil {
return q, "", bad("cursor", "invalid or does not match the current filter and sort")
}
q.After = &c
}
return q, fp, nil
}
func handleHealthz() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
encode(w, http.StatusOK, map[string]string{"status": "ok"})
})
}
// handleReadyz answers 503 while a dependency is down or the server is
// draining, so the load balancer stops sending traffic before shutdown.
func handleReadyz(ready func(context.Context) error) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ready != nil {
if err := ready(r.Context()); err != nil {
problem.Write(w, r, problem.New(http.StatusServiceUnavailable, "", "", err.Error()))
return
}
}
encode(w, http.StatusOK, map[string]string{"status": "ready"})
})
}
// writeError is the one place where domain errors become status codes.
func writeError(w http.ResponseWriter, r *http.Request, err error) {
var p *problem.Problem
switch {
case errors.Is(err, product.ErrNotFound):
p = problem.New(http.StatusNotFound, "", "", "no product with id "+r.PathValue("id"))
case errors.Is(err, product.ErrSKUTaken):
p = problem.New(http.StatusConflict, "sku-taken", "SKU already exists", "")
case errors.Is(err, product.ErrVersionMismatch):
p = staleProblem() // lost the race inside the repository's version check
case errors.Is(err, product.ErrInvalidTransition):
p = problem.New(http.StatusConflict, "invalid-transition", "Status change not allowed", err.Error())
default:
// The access-log middleware records the cause; the client gets no internals.
if rec, ok := w.(interface{ SetError(error) }); ok {
rec.SetError(err)
}
p = problem.New(http.StatusInternalServerError, "", "", "")
}
problem.Write(w, r, p)
}DTOs: request and response types Must-know
In plain words: A DTO (data transfer object) is a struct that exists only to be JSON on the wire: ProductWrite is what a client may send, ProductView is what it gets back. The domain type product.Product is never decoded from or encoded to JSON directly.
Common misunderstanding: "One struct with JSON tags for everything saves code." Then a client can set version or id by sending them, a new internal field leaks into every response the day it is added, renaming a Go field renames a public field, and you cannot have different shapes for create and read. Mat Ryer makes the same point about per-handler types: they prevent "other handlers from relying on data you may not consider stable".
Definition: a write DTO contains only client-writable fields, with JSON names, validation rules and a conversion to the domain input (Draft()); a view DTO contains the public representation and is built by a mapping function (View(p)), which is also where nil slices become [] and where fields can be hidden per audience. Go 1.24's omitzero tag option omits zero values that omitempty cannot (for example a zero time.Time); the release notes call it "clearer and less error-prone than omitempty".
wire HTTP adapter domain
1 {"sku":"MUG-1",...} ──────▶ dto.ProductWrite ── Draft() ──▶ product.Draft
2 service.Create -> product.Product
3 {"id":"prd_..",...} ◀────── dto.ProductView ◀── View(p) ── product.Product
4 {"id":"x"} in a POST ─────▶ unknown field "id": 400 (DisallowUnknownFields)Real scenario: an is_admin column that a client set to true through a mass-assigned update; a mobile app broken because a field was renamed during a refactor; an API that must return price as a string for one partner and an integer for others; a password_hash that appeared in a list response.
| Concern | Without DTOs | With DTOs |
|---|---|---|
| Mass assignment | Any JSON field reaches the model | Only fields in ProductWrite exist |
| Leaking internals | New struct fields are public | View lists every public field |
| Different shapes per operation | Impossible | One type per operation |
| Refactoring Go names | Breaks clients | Only JSON tags are the contract |
| Cost | Fewer types | Mapping functions to write and test |
Fix / how to use it: keep DTOs in their own package (dto) or inside the handler when only one handler uses them (Mat Ryer's inline type request struct). Encoding details of struct tags live in JSON, XML & Encoding.
// Package dto holds the wire types of the API: what clients send and what
// they get back. They are not the domain type, so the JSON contract can stay
// stable while product.Product evolves.
package dto
import (
"context"
"fmt"
"time"
"unicode/utf8"
"academy/rest-api-project/product"
"academy/rest-api-project/validation"
)
// ProductWrite is the body of POST, PUT and (after merge) PATCH. It carries
// both validation styles: the validate tags for go-playground/validator and
// a hand-written Valid method. The API uses Valid; the test proves they agree.
type ProductWrite struct {
SKU string `json:"sku" validate:"required,min=3,max=32"`
Name string `json:"name" validate:"required,max=200"`
PriceCents *int64 `json:"price_cents" validate:"required,gte=0,lte=100000000"` // pointer: absent or null is not 0
Currency string `json:"currency" validate:"len=3,uppercase"`
Status string `json:"status" validate:"oneof=draft active archived"`
Tags []string `json:"tags,omitempty" validate:"max=10,dive,min=1,max=30"`
}
// Valid is the hand-written validator: plain Go, no reflection, every rule
// visible and debuggable; it may use ctx for lookups (feature flags, tenant).
func (w ProductWrite) Valid(_ context.Context) []validation.Violation {
var v []validation.Violation
add := func(ptr, msg string) { v = append(v, validation.Violation{Pointer: ptr, Detail: msg}) }
switch n := utf8.RuneCountInString(w.SKU); { // characters, as the validator tags count
case n == 0:
add("/sku", "is required")
case n < 3:
add("/sku", "must be at least 3")
case n > 32:
add("/sku", "must be at most 32")
}
if w.Name == "" {
add("/name", "is required")
} else if utf8.RuneCountInString(w.Name) > 200 {
add("/name", "must be at most 200")
}
switch {
case w.PriceCents == nil:
add("/price_cents", "is required")
case *w.PriceCents < 0:
add("/price_cents", "must be at least 0")
case *w.PriceCents > 100_000_000:
add("/price_cents", "must be at most 100000000")
}
if utf8.RuneCountInString(w.Currency) != 3 {
add("/currency", "must have length 3")
} else if !isUpper(w.Currency) {
add("/currency", "must be upper case")
}
if !product.Status(w.Status).Valid() {
add("/status", "must be one of: draft active archived")
}
if len(w.Tags) > 10 {
add("/tags", "must be at most 10")
}
for i, t := range w.Tags {
if n := utf8.RuneCountInString(t); n < 1 {
add(fmt.Sprintf("/tags/%d", i), "must be at least 1")
} else if n > 30 {
add(fmt.Sprintf("/tags/%d", i), "must be at most 30")
}
}
return v
}
func isUpper(s string) bool {
for _, r := range s {
if r < 'A' || r > 'Z' {
return false
}
}
return true
}
// Cents is a helper for building a ProductWrite in Go code.
func Cents(n int64) *int64 { return &n }
// Draft converts the validated body to the domain input (Valid has checked
// that PriceCents is set).
func (w ProductWrite) Draft() product.Draft {
return product.Draft{SKU: w.SKU, Name: w.Name, PriceCents: *w.PriceCents, Currency: w.Currency, Status: product.Status(w.Status), Tags: w.Tags}
}
// WriteOf is the inverse, used by PATCH to build the document the merge
// patch is applied to.
func WriteOf(p product.Product) ProductWrite {
return ProductWrite{SKU: p.SKU, Name: p.Name, PriceCents: Cents(p.PriceCents), Currency: p.Currency, Status: string(p.Status), Tags: p.Tags}
}
// ProductView is the response representation, the Go counterpart of a
// Laravel API Resource's toArray.
type ProductView struct {
ID string `json:"id"`
SKU string `json:"sku"`
Name string `json:"name"`
PriceCents int64 `json:"price_cents"`
Currency string `json:"currency"`
Status string `json:"status"`
Tags []string `json:"tags"`
Version int64 `json:"version"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// View maps the aggregate to its representation.
func View(p product.Product) ProductView {
tags := p.Tags
if tags == nil {
tags = []string{} // "tags": [] rather than null
}
return ProductView{ID: p.ID, SKU: p.SKU, Name: p.Name, PriceCents: p.PriceCents, Currency: p.Currency,
Status: string(p.Status), Tags: tags, Version: p.Version, CreatedAt: p.CreatedAt, UpdatedAt: p.UpdatedAt}
}
// ListView is the collection envelope: data plus the cursor for the next
// page (also sent as a Link header).
type ListView struct {
Data []ProductView `json:"data"`
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more"`
}Request validation: go-playground/validator vs hand-written Validate() Must-know
In plain words: After the body is decoded, check that every field makes sense (SKU length, non-negative price, a known status) and report every problem at once, each pointing at its field. You can write the checks as plain Go in a Valid method or declare them as struct tags read by go-playground/validator.
Common misunderstanding: "Validation and business rules are the same thing." Validation is about the shape of one request and needs no database (422). A rule such as "an archived product cannot be re-activated" or "the SKU must be unique" depends on stored state and belongs to the service or the database (409). Mixing them puts SQL in your validator or shape checks in your service.
Definition: the hand-written style follows Mat Ryer's Validator interface, Valid(ctx context.Context) (problems map[string]string); the chapter returns []validation.Violation{Pointer, Detail} so the result maps straight to RFC 9457 errors with JSON Pointers (RFC 6901). The tag style uses validator.New(validator.WithRequiredStructEnabled()) (the README: "highly recommended ... opt-in to new behaviour that will become the default behaviour in v11+"), RegisterTagNameFunc to report JSON names, and converts validator.ValidationErrors into the same violations. Lengths are counted in characters on both sides (the validator doc: "the string length is at most that number of characters"), so the hand-written code uses utf8.RuneCountInString, not len. price_cents is a *int64 with required: a missing member or a merge-patch null is a 422 "is required", not a silent 0. The test proves both styles produce identical output for the same bodies, non-ASCII ones included.
1 decode {"sku":"AB","name":"","price_cents":-1,"currency":"eur","status":"sold"} ok: valid JSON
2 Valid /sku must be at least 3 · /name is required · /price_cents must be at least 0
/currency must be upper case · /status must be one of: draft active archived
3 422 application/problem+json, type .../validation, errors[5]
4 service SKU unique? archived frozen? -> 409 if not (business rules, not validation)Real scenario: a form that needs every error at once, not one per submit; a mobile client that highlights the exact field (/tags/2); a partner integration that must get the same error format from every endpoint; a rule that depends on the tenant's plan (ctx lets Valid look it up).
Hand-written Valid(ctx) | go-playground/validator tags | |
|---|---|---|
| Dependencies | None (stdlib) | github.com/go-playground/validator/v10 (v10.30.1 here) |
| Rules visible | In Go code, debuggable | In tag strings (required,min=3,max=32) |
| Cross-field rules | Plain if | required_if, gtfield, custom funcs |
| Context-aware rules | ctx parameter | StructCtx and custom validators |
| Error messages | Yours | Build from FieldError.Tag()/Param() or use translations |
| Speed of writing many rules | Slower | Faster |
| Used by | Mat Ryer's pattern, many stdlib-first services | Gin's default binding validator |
Fix / how to use it: pick one style per service and convert its output to one Violation type; do not let the validator's own error strings reach clients.
// Package validation holds the one type both validation styles produce, a
// Violation addressed by a JSON Pointer, and the tag-based style built on
// github.com/go-playground/validator/v10.
package validation
import (
"errors"
"fmt"
"reflect"
"strings"
"github.com/go-playground/validator/v10"
)
// Violation is one problem with one field of the request body. Pointer is an
// RFC 6901 JSON Pointer such as "/price_cents" or "/tags/2".
type Violation struct {
Pointer string `json:"pointer"`
Detail string `json:"detail"`
}
// Tags validates structs by their `validate:"..."` tags and reports fields by
// their JSON names, not their Go names.
type Tags struct {
v *validator.Validate
}
// NewTags builds the validator once; it caches struct metadata, so share it.
func NewTags() *Tags {
v := validator.New(validator.WithRequiredStructEnabled())
v.RegisterTagNameFunc(func(f reflect.StructField) string {
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if name == "-" {
return ""
}
return name
})
return &Tags{v: v}
}
// Struct returns nil or the list of violations for s.
func (t *Tags) Struct(s any) []Violation {
err := t.v.Struct(s)
if err == nil {
return nil
}
var ves validator.ValidationErrors
if !errors.As(err, &ves) {
// InvalidValidationError: a programming error (nil or non-struct).
panic(err)
}
out := make([]Violation, 0, len(ves))
for _, fe := range ves {
out = append(out, Violation{Pointer: pointer(fe.Namespace()), Detail: message(fe)})
}
return out
}
// pointer turns validator's namespace "productWrite.tags[2]" into "/tags/2".
func pointer(ns string) string {
_, rest, _ := strings.Cut(ns, ".")
rest = strings.NewReplacer("[", ".", "]", "").Replace(rest)
return "/" + strings.ReplaceAll(rest, ".", "/")
}
func message(fe validator.FieldError) string {
switch fe.Tag() {
case "required":
return "is required"
case "min", "gte":
return fmt.Sprintf("must be at least %s", fe.Param())
case "max", "lte":
return fmt.Sprintf("must be at most %s", fe.Param())
case "oneof":
return fmt.Sprintf("must be one of: %s", fe.Param())
case "len":
return fmt.Sprintf("must have length %s", fe.Param())
case "uppercase":
return "must be upper case"
}
return "failed rule " + fe.Tag()
}package dto
import (
"slices"
"strings"
"testing"
"academy/rest-api-project/validation"
)
// Both validation styles must report the same JSON pointers and messages for
// the same body, so either can back the 422 problem response.
func TestHandWrittenAndTagValidationAgree(t *testing.T) {
tags := validation.NewTags()
bodies := []ProductWrite{
{},
{SKU: "AB", Name: "x", PriceCents: Cents(-5), Currency: "eur", Status: "sold", Tags: []string{"ok", ""}},
{SKU: "MUG-1", Name: "Mug", PriceCents: Cents(900), Currency: "EUR", Status: "active"},
}
// Non-ASCII: limits count characters, not bytes (validator doc: "the number
// of characters"). "éé" is 2 characters (4 bytes): too short; 101 "é" are
// 101 characters (202 bytes): within the 200 limit.
bodies = append(bodies,
ProductWrite{SKU: "éé", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active"},
ProductWrite{SKU: "TAS-1", Name: strings.Repeat("é", 101), PriceCents: Cents(900), Currency: "EUR", Status: "active"},
ProductWrite{SKU: "TAS-2", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active", Tags: []string{strings.Repeat("ü", 30)}},
)
for i, b := range bodies {
hand := b.Valid(t.Context())
byTag := tags.Struct(b)
if !slices.Equal(hand, byTag) {
t.Errorf("body %d:\n hand %v\n tags %v", i, hand, byTag)
}
}
}
func TestNonASCIIIsCountedInCharacters(t *testing.T) {
short := ProductWrite{SKU: "éé", Name: "Tasse", PriceCents: Cents(900), Currency: "EUR", Status: "active"}
if v := short.Valid(t.Context()); len(v) != 1 || v[0].Pointer != "/sku" {
t.Fatalf("2-character SKU: %v", v)
}
long := ProductWrite{SKU: "TAS-1", Name: strings.Repeat("é", 101), PriceCents: Cents(900), Currency: "EUR", Status: "active"}
if v := long.Valid(t.Context()); v != nil {
t.Fatalf("101-character name: %v", v)
}
}The error envelope: problem details RFC 9457 Must-know
In plain words: Every error from the API has the same JSON shape, sent with Content-Type: application/problem+json: a type URI that names the kind of problem, a short title, the status, an optional detail for this occurrence, the instance path, and extra members you define (here errors and request_id).
Common misunderstanding: "Clients should read the message." RFC 9457: "Consumers SHOULD NOT parse the "detail" member for information; extensions are more suitable and less error-prone ways to obtain such information." Clients switch on type (and the HTTP status), never on text. And the status in the body is not a replacement for the real one: "Generators MUST use the same status code in the actual HTTP response".
Definition: a problem details object has the members type (default about:blank, which "indicates that the problem has no additional semantics beyond that of the HTTP status code"; then the title "SHOULD be the same as the recommended HTTP status phrase"), title, status, detail, instance, plus extension members, which clients "MUST ignore" when they do not recognise them. RFC 9457's own validation example uses an errors array of objects with detail and a JSON Pointer pointer, which the chapter adopts. Problem details "are not a debugging tool for the underlying implementation": no stack traces, SQL or internal hostnames.
1 handler gets product.ErrVersionMismatch
2 writeError: errors.Is(...) -> problem.New(412, "stale-version", "Resource changed since you read it", hint)
3 problem.Write: Content-Type application/problem+json, Cache-Control no-store, status 412
4 body {"type":"https://api.example.test/problems/stale-version","title":...,"status":412,
"instance":"/v1/products/prd_...","request_id":"4fc986c41e92388b"}
5 client: switch on type -> re-GET, re-apply, retryReal scenario: a generated TypeScript client that turns every non-2xx into one ProblemError class; support finding the log line from the request_id a customer pasted; a validation UI that maps each pointer to a form field; a gateway that adds its own problem types (rate-limited) without breaking clients.
| API | Error shape | Machine-readable code |
|---|---|---|
| This chapter | RFC 9457 + errors[] + request_id | type URI |
| Stripe | {"error": {"type", "code", "message", "param", ...} } | type + code |
| Google AIPs (AIP-193) | google.rpc.Status with details | Canonical code + ErrorInfo.reason |
| Laravel default (validation) | {"message", "errors": {"field": ["..."]} }, 422 | Field keys |
| JSON:API | {"errors": [{"status","code","title","source": {"pointer"} } ] } | code |
Fix / how to use it: one constructor package, one Write function, one writeError mapping; register a documentation page for each type URI.
// Package problem writes RFC 9457 Problem Details: the one error envelope
// every endpoint of the API returns.
package problem
import (
"encoding/json"
"net/http"
"academy/rest-api-project/validation"
)
// MediaType is the content type registered by RFC 9457.
const MediaType = "application/problem+json"
// TypeBase is where the human-readable documentation of each problem type
// lives. Clients switch on Type, never on Title or Detail.
const TypeBase = "https://api.example.test/problems/"
// Problem is the RFC 9457 object plus two extension members: errors (one
// entry per invalid field) and request_id (to find the log line).
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail,omitempty"`
Instance string `json:"instance,omitempty"`
Errors []validation.Violation `json:"errors,omitempty"`
RequestID string `json:"request_id,omitempty"`
}
// New builds a problem whose type is TypeBase+slug, or about:blank when slug
// is empty (then the title must be the status phrase, per RFC 9457 4.2.1).
func New(status int, slug, title, detail string) *Problem {
p := &Problem{Type: "about:blank", Title: http.StatusText(status), Status: status, Detail: detail}
if slug != "" {
p.Type = TypeBase + slug
p.Title = title
}
return p
}
// Validation is the 422 problem with one entry per violation.
func Validation(v []validation.Violation) *Problem {
p := New(http.StatusUnprocessableEntity, "validation", "Request body failed validation", "")
p.Errors = v
return p
}
// Write sends p with the same status in the header and the body, as the RFC
// requires ("Generators MUST use the same status code").
func Write(w http.ResponseWriter, r *http.Request, p *Problem) {
if p.Instance == "" {
p.Instance = r.URL.Path
}
if p.RequestID == "" {
p.RequestID = w.Header().Get("X-Request-ID") // set by the request-id middleware
}
w.Header().Set("Content-Type", MediaType)
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(p.Status)
_ = json.NewEncoder(w).Encode(p)
}Status codes Must-know
In plain words: The status code is the first thing every client, proxy, retry library and dashboard reads. Pick it by asking who must act: 2xx nothing to do, 4xx the client must change something, 5xx the server failed and a retry may help.
Common misunderstanding: "400 for every client error is simpler." A client cannot fix "your JSON is broken" (400), "your JSON is fine but the price is negative" (422), "someone changed this since you read it" (412) and "you forgot If-Match" (428) the same way, and retry libraries treat 409 and 429 specially. The opposite mistake is inventing codes or using 500 for "not found".
Definition: the codes this API uses, with their RFC and the condition that triggers each in the snippets, are in the table. Go names them as constants in net/http (http.StatusUnprocessableEntity, http.StatusPreconditionRequired); the status.go source annotates each with its RFC section.
1 bytes arrive Content-Type? 415 · too big? 413 · not JSON / unknown field? 400
2 JSON decoded rules broken? 422 with errors[]
3 If-Match missing? 428 · stale? 412
4 service no such id? 404 · SKU taken / frozen status? 409
5 success 201 + Location (create) · 200 (read, update) · 204 (delete) · 304 (not modified)
6 overload, failure 429 + Retry-After · 503 not ready · 500 bug (cause logged, not sent)Real scenario: a retry library that retries 503 and 429 but never 422; a CDN that caches 404s; an alert on the 5xx rate that must not fire for validation errors; a client that shows "someone else edited this" on 412.
| Code | Name (RFC 9110 unless noted) | This API returns it when | Client should |
|---|---|---|---|
| 200 | OK | Read, PUT, PATCH succeeded | Use the body |
| 201 | Created | POST created; Location + ETag sent | Store the ID or follow Location |
| 204 | No Content | DELETE succeeded | Nothing |
| 304 | Not Modified | If-None-Match equals the current ETag | Use its cached copy |
| 400 | Bad Request | Malformed JSON, unknown field, wrong JSON type, bad query or cursor, two JSON values | Fix the request |
| 404 | Not Found | No product with that id; unknown path | Stop or re-list |
| 405 | Method Not Allowed | Path exists, method does not; Allow lists methods | Use a listed method |
| 409 | Conflict | Duplicate SKU; forbidden status change; same Idempotency-Key still in flight | Change data, or retry later for in-flight |
| 412 | Precondition Failed | If-Match does not match the current ETag | Re-GET, re-apply, retry |
| 413 | Content Too Large | Body over API_MAX_BODY_BYTES (http.MaxBytesError) | Send less |
| 415 | Unsupported Media Type | Content-Type is not application/json (or application/merge-patch+json for PATCH) | Send the right type |
| 422 | Unprocessable Content | Valid JSON that fails validation; Idempotency-Key reused with another body | Fix fields named in errors |
| 428 | Precondition Required (RFC 6585) | PUT/PATCH/DELETE without If-Match | Send the ETag |
| 429 | Too Many Requests (RFC 6585) | The rate limiting hook said no; Retry-After set | Wait, then retry |
| 500 | Internal Server Error | Unmapped error or panic | Retry later only if idempotent |
| 503 | Service Unavailable | /readyz during shutdown or when a dependency is down | Go elsewhere (load balancer) |
Fix / how to use it: map errors to codes in exactly one function (writeError above) and test each code once end to end, as TestRequestErrorsAreProblems and TestCRUDLifecycle do.
Repository pattern: one interface per aggregate Must-know
In plain words: The service does not talk to SQL; it talks to a small interface, service.Repository, with the five operations it needs on products. A PostgreSQL type and an in-memory type both implement it, so the same service runs in tests and in production.
Common misunderstanding: "A generic Repository[T] with FindAll, FindBy(map), Save covers every table." Generic repositories leak the query language back into the service (FindBy(map[string]any{"status": ...})), cannot express keyset pagination or optimistic locking cleanly, and turn every aggregate into a table. One interface per aggregate, named for what the use cases need, keeps both sides honest. The other misunderstanding is the reverse: "the repository package defines the interface". In Go the consumer defines it, so service owns Repository and pgrepo simply has the right methods.
Definition: a repository mediates between the domain and storage for one aggregate root (the DDD meaning, see Repositories). Its methods speak domain types and domain errors (product.ErrNotFound, ErrSKUTaken, ErrVersionMismatch), never sql.ErrNoRows or SQLSTATE codes. List returns Limit+1 rows so the service can tell whether another page exists without a COUNT. Compile-time checks var _ service.Repository = (*memrepo.Repo)(nil) sit in the tests of both implementations.
1 service.Replace(ctx, id, ifVersion=1, draft)
2 repo.Get(ctx, id) -> product v1
3 rule: CanTransition(v1.Status, draft.Status)
4 repo.Update(ctx, v2, expected=1)
pgrepo: UPDATE ... WHERE id = $1 AND version = $9 -> 1 row
memrepo: lock; cur.Version == 1? store -> ok
5 concurrent writer with expected=1 -> 0 rows -> ErrVersionMismatch -> 412Real scenario: unit tests of a pricing rule that run in microseconds against memrepo; moving one aggregate from PostgreSQL to DynamoDB without touching handlers; a read model served from a replica behind the same interface; an auditing decorator that wraps any Repository.
| Option | What the service depends on | Good for | Cost |
|---|---|---|---|
*sql.DB in the service | SQL text, driver errors | Tiny tools | No unit tests without a database |
Generic Repository[T] | Query-by-map | CRUD admin panels | Leaky, weak types, no keyset |
| Interface per aggregate (this chapter) | Domain methods and errors | Services with rules | One interface and two implementations |
| sqlc / generated queries + thin repo | Generated typed queries (its README: "sqlc generates type-safe code from SQL") | SQL-first teams | Generation step |
| ORM (GORM, "The fantastic ORM library for Golang"; ent, "An Entity Framework For Go") behind a repo | ORM types inside the repo only | Teams that want an ORM | ORM behaviour to learn (ORM pitfalls) |
Fix / how to use it: the in-memory implementation runs the same keyset algorithm as the SQL one, so pagination is tested without a database; the PostgreSQL implementation uses database/sql with an allow-listed ORDER BY and maps SQLSTATE 23505 through the SQLState() method that both pgx's *pgconn.PgError (func (pe *PgError) SQLState() string) and lib/pq's *pq.Error (func (e *Error) SQLState() string) define. tags is stored as jsonb and sent as JSON text, which works the same through any driver (a text[] column would need driver-specific array encoding). Both implementations also have Ping for the readiness probe. Without a PostgreSQL server, TestTagsRoundTrip drives the repository through a small fake database/sql driver that keeps exactly the columns the SQL names, so a column left out of INSERT, UPDATE or SELECT fails the test. Pools, transactions and pgx specifics are in database/sql & pgx.
// Package memrepo is an in-memory service.Repository: same contract as the
// PostgreSQL one, used by unit and end-to-end tests and by the demo binary.
package memrepo
import (
"context"
"slices"
"sync"
"academy/rest-api-project/product"
)
// Repo is safe for concurrent use.
type Repo struct {
mu sync.RWMutex
byID map[string]product.Product
bySKU map[string]string
}
// New returns an empty repository.
func New() *Repo {
return &Repo{byID: map[string]product.Product{}, bySKU: map[string]string{}}
}
func (r *Repo) Insert(ctx context.Context, p product.Product) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
if _, taken := r.bySKU[p.SKU]; taken {
return product.ErrSKUTaken
}
r.byID[p.ID] = clone(p)
r.bySKU[p.SKU] = p.ID
return nil
}
func (r *Repo) Get(ctx context.Context, id string) (product.Product, error) {
if err := ctx.Err(); err != nil {
return product.Product{}, err
}
r.mu.RLock()
defer r.mu.RUnlock()
p, ok := r.byID[id]
if !ok {
return product.Product{}, product.ErrNotFound
}
return clone(p), nil
}
func (r *Repo) Update(ctx context.Context, p product.Product, expected int64) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
cur, ok := r.byID[p.ID]
if !ok {
return product.ErrNotFound
}
if cur.Version != expected {
return product.ErrVersionMismatch
}
if owner, taken := r.bySKU[p.SKU]; taken && owner != p.ID {
return product.ErrSKUTaken
}
delete(r.bySKU, cur.SKU)
r.bySKU[p.SKU] = p.ID
r.byID[p.ID] = clone(p)
return nil
}
func (r *Repo) Delete(ctx context.Context, id string, expected int64) error {
if err := ctx.Err(); err != nil {
return err
}
r.mu.Lock()
defer r.mu.Unlock()
cur, ok := r.byID[id]
if !ok {
return product.ErrNotFound
}
if cur.Version != expected {
return product.ErrVersionMismatch
}
delete(r.byID, id)
delete(r.bySKU, cur.SKU)
return nil
}
// List filters, sorts by (field, id) and seeks past the cursor: the same
// keyset algorithm the SQL version runs in the database.
func (r *Repo) List(ctx context.Context, q product.ListQuery) ([]product.Product, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
r.mu.RLock()
var rows []product.Product
for _, p := range r.byID {
if match(p, q) {
rows = append(rows, clone(p))
}
}
r.mu.RUnlock()
sign := 1
if q.Desc {
sign = -1
}
slices.SortFunc(rows, func(a, b product.Product) int {
return sign * product.Compare(product.CursorAfter(a), product.CursorAfter(b), q.Sort)
})
out := rows[:0]
for _, p := range rows {
if q.After != nil && sign*product.Compare(product.CursorAfter(p), *q.After, q.Sort) <= 0 {
continue
}
out = append(out, p)
if len(out) == q.Limit+1 {
break
}
}
return out, nil
}
// Ping lets the readiness probe ask the store if it is usable.
func (r *Repo) Ping(ctx context.Context) error { return ctx.Err() }
func match(p product.Product, q product.ListQuery) bool {
if q.Status != "" && p.Status != q.Status {
return false
}
if q.MinPrice != nil && p.PriceCents < *q.MinPrice {
return false
}
if q.MaxPrice != nil && p.PriceCents > *q.MaxPrice {
return false
}
return true
}
func clone(p product.Product) product.Product {
p.Tags = slices.Clone(p.Tags)
return p
}// Package pgrepo is the PostgreSQL service.Repository on database/sql. It
// imports no driver: main registers one (pgx's stdlib adapter, for example).
package pgrepo
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"academy/rest-api-project/product"
)
// Schema is the table the repository expects (normally a migration file).
const Schema = `
CREATE TABLE products (
id text PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
currency char(3) NOT NULL,
status text NOT NULL,
tags jsonb NOT NULL DEFAULT '[]',
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX products_created_id ON products (created_at, id);
CREATE INDEX products_price_id ON products (price_cents, id);
CREATE INDEX products_name_id ON products (name, id);`
// Repo implements service.Repository.
type Repo struct {
db *sql.DB
}
// New takes the pool; the caller owns its lifetime.
func New(db *sql.DB) *Repo { return &Repo{db: db} }
// Ping backs the readiness probe, like memrepo.Repo.Ping.
func (r *Repo) Ping(ctx context.Context) error { return r.db.PingContext(ctx) }
func (r *Repo) Get(ctx context.Context, id string) (product.Product, error) {
row := r.db.QueryRowContext(ctx, `SELECT `+columns+` FROM products WHERE id = $1`, id)
p, err := scan(row)
if errors.Is(err, sql.ErrNoRows) {
return product.Product{}, product.ErrNotFound
}
return p, err
}
// Update is optimistic concurrency in one statement: the WHERE clause on
// version makes a stale write affect zero rows.
func (r *Repo) Update(ctx context.Context, p product.Product, expected int64) error {
res, err := r.db.ExecContext(ctx, `
UPDATE products SET sku = $2, name = $3, price_cents = $4, currency = $5,
status = $6, version = $7, updated_at = $8, tags = $10
WHERE id = $1 AND version = $9`,
p.ID, p.SKU, p.Name, p.PriceCents, p.Currency, p.Status, p.Version, p.UpdatedAt, expected, tagsJSON(p.Tags))
if err != nil {
return mapErr(err)
}
if n, _ := res.RowsAffected(); n == 0 {
if _, err := r.Get(ctx, p.ID); err != nil {
return err // ErrNotFound
}
return product.ErrVersionMismatch
}
return nil
}
func (r *Repo) Insert(ctx context.Context, p product.Product) error {
_, err := r.db.ExecContext(ctx, `
INSERT INTO products (id, sku, name, price_cents, currency, status, tags, version, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
p.ID, p.SKU, p.Name, p.PriceCents, p.Currency, p.Status, tagsJSON(p.Tags), p.Version, p.CreatedAt, p.UpdatedAt)
return mapErr(err)
}
func (r *Repo) Delete(ctx context.Context, id string, expected int64) error {
res, err := r.db.ExecContext(ctx, `DELETE FROM products WHERE id = $1 AND version = $2`, id, expected)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
if _, err := r.Get(ctx, id); err != nil {
return err
}
return product.ErrVersionMismatch
}
return nil
}
func (r *Repo) List(ctx context.Context, q product.ListQuery) ([]product.Product, error) {
query, args := BuildList(q)
rows, err := r.db.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var out []product.Product
for rows.Next() {
p, err := scan(rows)
if err != nil {
return nil, err
}
out = append(out, p)
}
return out, rows.Err()
}
// sortColumns is an allow-list: user input never becomes SQL text.
var sortColumns = map[product.SortField]string{
product.SortCreatedAt: "created_at",
product.SortPrice: "price_cents",
product.SortName: "name",
}
// BuildList renders filter + keyset seek + order + limit. The row-value
// comparison (col, id) > ($n, $m) matches the (col, id) index exactly.
func BuildList(q product.ListQuery) (string, []any) {
col, ok := sortColumns[q.Sort]
if !ok {
col = "created_at"
}
var where []string
var args []any
arg := func(v any) string { args = append(args, v); return fmt.Sprintf("$%d", len(args)) }
if q.Status != "" {
where = append(where, "status = "+arg(string(q.Status)))
}
if q.MinPrice != nil {
where = append(where, "price_cents >= "+arg(*q.MinPrice))
}
if q.MaxPrice != nil {
where = append(where, "price_cents <= "+arg(*q.MaxPrice))
}
op, dir := ">", "ASC"
if q.Desc {
op, dir = "<", "DESC"
}
if c := q.After; c != nil {
var v any = c.CreatedAt
switch q.Sort {
case product.SortPrice:
v = c.PriceCents
case product.SortName:
v = c.Name
}
where = append(where, fmt.Sprintf("(%s, id) %s (%s, %s)", col, op, arg(v), arg(c.ID)))
}
var b strings.Builder
b.WriteString("SELECT " + columns + " FROM products")
if len(where) > 0 {
b.WriteString(" WHERE " + strings.Join(where, " AND "))
}
fmt.Fprintf(&b, " ORDER BY %s %s, id %s LIMIT %s", col, dir, dir, arg(q.Limit+1))
return b.String(), args
}
// tags is stored as jsonb and sent as JSON text: driver-independent, unlike
// text[], whose array encoding differs between pgx and lib/pq.
const columns = "id, sku, name, price_cents, currency, status, tags, version, created_at, updated_at"
func tagsJSON(tags []string) string {
if tags == nil {
tags = []string{}
}
b, _ := json.Marshal(tags)
return string(b)
}
type scanner interface{ Scan(dest ...any) error }
func scan(s scanner) (product.Product, error) {
var p product.Product
var tags []byte
err := s.Scan(&p.ID, &p.SKU, &p.Name, &p.PriceCents, &p.Currency, &p.Status, &tags, &p.Version, &p.CreatedAt, &p.UpdatedAt)
if err == nil && len(tags) > 0 {
err = json.Unmarshal(tags, &p.Tags)
}
return p, err
}
// mapErr turns a unique violation (SQLSTATE 23505) into the domain error.
// pgx's *pgconn.PgError and lib/pq's *pq.Error both expose SQLState().
func mapErr(err error) error {
var st interface{ SQLState() string }
if errors.As(err, &st) && st.SQLState() == "23505" {
return product.ErrSKUTaken
}
return err
}Service layer Must-know
In plain words: The service holds the use cases (create, get, list, replace, delete) and the rules that need stored state. It is plain Go that an HTTP handler, a gRPC method, a CLI command or a queue consumer can all call.
Common misunderstanding: "The service layer is boilerplate that just forwards to the repository." For Get it is; for Replace it is where the version check, the status rule and the timestamps live, and where a transaction or an outbox write would go. Without it those rules end up in the handler, and the next transport (a consumer, an admin CLI) re-implements them differently.
Definition: a service is a struct built by a constructor that receives every dependency (service.New(repo, now, newID)), with methods that take ctx first and domain inputs, and return domain outputs and domain errors. It owns the interfaces it consumes. It never imports net/http. PUT and PATCH both end in one method, Replace(ctx, id, ifVersion, draft), so the rules cannot differ between them.
1 handler PATCH merge -> decode -> Valid -> svc.Replace(ctx, id, ifVersion, draft)
2 handler PUT decode -> Valid ----------> svc.Replace(ctx, id, ifVersion, draft)
3 CLI "archive" draft.Status = archived --> svc.Replace(ctx, id, ifVersion, draft)
4 Replace: Get -> version check -> CanTransition -> stamp UpdatedAt -> Version+1 -> repo.UpdateReal scenario: a product import job that must obey the same "archived is frozen" rule as the API; a price change that must also write an audit row in the same transaction; an event ProductRepriced published through an outbox from one place; a clock injected so tests can assert timestamps.
| Logic | Lives in | Example |
|---|---|---|
| Shape of one request | DTO Valid | price_cents >= 0 |
| HTTP protocol | Handler | If-Match parsing, 201 + Location |
| Rules needing state | Service | Archived is frozen; version must match |
| Invariants of one value | Domain (product) | CanTransition, Status.Valid |
| Uniqueness under concurrency | Database | UNIQUE (sku), mapped to ErrSKUTaken |
Fix / how to use it: the domain package holds the aggregate, its errors, the transition rule and the keyset ordering; the service uses them.
// Package product is the domain model of the chapter's API: one aggregate,
// its invariants and the errors the rest of the code maps to HTTP.
package product
import (
"errors"
"time"
)
// Status is the lifecycle state of a product.
type Status string
const (
StatusDraft Status = "draft"
StatusActive Status = "active"
StatusArchived Status = "archived"
)
// Valid reports whether s is one of the known states.
func (s Status) Valid() bool {
switch s {
case StatusDraft, StatusActive, StatusArchived:
return true
}
return false
}
// Product is the aggregate root. Version increments on every change and is
// what the HTTP layer exposes as the ETag.
type Product struct {
ID string
SKU string
Name string
PriceCents int64
Currency string
Status Status
Tags []string
Version int64
CreatedAt time.Time
UpdatedAt time.Time
}
// Draft holds the client-writable fields, shared by create, replace and patch.
type Draft struct {
SKU string
Name string
PriceCents int64
Currency string
Status Status
Tags []string
}
// Domain errors. Callers compare with errors.Is; the HTTP layer maps them to
// status codes in exactly one place.
var (
ErrNotFound = errors.New("product not found")
ErrSKUTaken = errors.New("sku already exists")
ErrVersionMismatch = errors.New("version mismatch")
ErrInvalidTransition = errors.New("invalid status transition")
)
// CanTransition encodes the business rule that an archived product is frozen:
// it can only stay archived.
func CanTransition(from, to Status) bool {
if from == StatusArchived {
return to == StatusArchived
}
return to.Valid()
}
// SortField names the columns a list can be ordered by.
type SortField string
const (
SortCreatedAt SortField = "created_at"
SortPrice SortField = "price"
SortName SortField = "name"
)
// ListQuery is a filtered, sorted, keyset-paginated read of the collection.
type ListQuery struct {
Status Status // empty: any status
MinPrice *int64 // inclusive, cents
MaxPrice *int64 // inclusive, cents
Sort SortField
Desc bool
After *Cursor // nil: first page
Limit int
}
// Cursor is the keyset position: the sort value and the id of the last row
// of the previous page. Only the field that matches Sort is meaningful.
type Cursor struct {
CreatedAt time.Time `json:"c,omitzero"`
PriceCents int64 `json:"p,omitempty"`
Name string `json:"n,omitempty"`
ID string `json:"i"`
}
// CursorAfter builds the cursor that continues after p.
func CursorAfter(p Product) Cursor {
return Cursor{CreatedAt: p.CreatedAt, PriceCents: p.PriceCents, Name: p.Name, ID: p.ID}
}
// Only keeps the field the list is sorted by (and the id), so the page token
// carries nothing else about the row.
func (c Cursor) Only(field SortField) Cursor {
out := Cursor{ID: c.ID}
switch field {
case SortPrice:
out.PriceCents = c.PriceCents
case SortName:
out.Name = c.Name
default:
out.CreatedAt = c.CreatedAt
}
return out
}
// Compare orders a and b by field, breaking ties by ID so the order is total,
// which keyset pagination requires.
func Compare(a, b Cursor, field SortField) int {
var c int
switch field {
case SortPrice:
c = cmpInt(a.PriceCents, b.PriceCents)
case SortName:
c = cmpString(a.Name, b.Name)
default:
c = a.CreatedAt.Compare(b.CreatedAt)
}
if c != 0 {
return c
}
return cmpString(a.ID, b.ID)
}
func cmpInt(a, b int64) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}
func cmpString(a, b string) int {
switch {
case a < b:
return -1
case a > b:
return 1
}
return 0
}// Package service is the application layer: use cases on the product
// aggregate. It knows nothing about HTTP or SQL; it owns the Repository
// interface it needs (the consumer defines the interface).
package service
import (
"context"
"fmt"
"slices"
"time"
"academy/rest-api-project/product"
)
// Repository is the persistence port for one aggregate. Implementations:
// memrepo (tests, demos) and pgrepo (PostgreSQL).
type Repository interface {
Insert(ctx context.Context, p product.Product) error
Get(ctx context.Context, id string) (product.Product, error)
// Update stores p only if the stored version equals expected.
Update(ctx context.Context, p product.Product, expected int64) error
Delete(ctx context.Context, id string, expected int64) error
// List returns up to q.Limit+1 rows so the caller can tell if more exist.
List(ctx context.Context, q product.ListQuery) ([]product.Product, error)
}
// Service wires the use cases to their dependencies, all passed in.
type Service struct {
repo Repository
now func() time.Time
newID func() string
}
// New is the only way to build a Service: dependency injection via the
// constructor, no globals, no container.
func New(repo Repository, now func() time.Time, newID func() string) *Service {
return &Service{repo: repo, now: now, newID: newID}
}
// Create stores a new product at version 1.
func (s *Service) Create(ctx context.Context, d product.Draft) (product.Product, error) {
at := s.now().UTC()
p := apply(product.Product{ID: s.newID(), Version: 1, CreatedAt: at}, d, at)
if err := s.repo.Insert(ctx, p); err != nil {
return product.Product{}, fmt.Errorf("create %s: %w", d.SKU, err)
}
return p, nil
}
// Get loads one product.
func (s *Service) Get(ctx context.Context, id string) (product.Product, error) {
return s.repo.Get(ctx, id)
}
// Page is one page of a list and the position to continue from.
type Page struct {
Items []product.Product
Next *product.Cursor
}
// List reads one page; q.Limit must already be clamped.
func (s *Service) List(ctx context.Context, q product.ListQuery) (Page, error) {
rows, err := s.repo.List(ctx, q)
if err != nil {
return Page{}, err
}
if len(rows) <= q.Limit {
return Page{Items: rows}, nil
}
rows = rows[:q.Limit]
next := product.CursorAfter(rows[len(rows)-1]).Only(q.Sort)
return Page{Items: rows, Next: &next}, nil
}
// Replace is the single write path for PUT and PATCH: the caller sends the
// full new state and the version it last saw (from If-Match).
func (s *Service) Replace(ctx context.Context, id string, ifVersion int64, d product.Draft) (product.Product, error) {
cur, err := s.repo.Get(ctx, id)
if err != nil {
return product.Product{}, err
}
if cur.Version != ifVersion {
return product.Product{}, product.ErrVersionMismatch
}
if !product.CanTransition(cur.Status, d.Status) {
return product.Product{}, fmt.Errorf("%w: %s -> %s", product.ErrInvalidTransition, cur.Status, d.Status)
}
next := apply(cur, d, s.now().UTC())
next.Version = cur.Version + 1
if err := s.repo.Update(ctx, next, cur.Version); err != nil {
return product.Product{}, err
}
return next, nil
}
// Delete removes a product if the client saw its latest version.
func (s *Service) Delete(ctx context.Context, id string, ifVersion int64) error {
return s.repo.Delete(ctx, id, ifVersion)
}
func apply(p product.Product, d product.Draft, at time.Time) product.Product {
p.SKU, p.Name, p.PriceCents, p.Currency, p.Status = d.SKU, d.Name, d.PriceCents, d.Currency, d.Status
p.Tags = slices.Clone(d.Tags)
p.UpdatedAt = at
return p
}package service_test
import (
"errors"
"testing"
"time"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
func newService() *service.Service {
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
n := 0
return service.New(memrepo.New(),
func() time.Time { at = at.Add(time.Second); return at },
func() string { n++; return "prd_" + string(rune('a'+n-1)) })
}
func TestReplaceRequiresCurrentVersion(t *testing.T) {
s := newService()
ctx := t.Context()
p, err := s.Create(ctx, product.Draft{SKU: "MUG-1", Name: "Mug", PriceCents: 900, Currency: "EUR", Status: product.StatusDraft})
if err != nil {
t.Fatal(err)
}
d := product.Draft{SKU: "MUG-1", Name: "Mug", PriceCents: 1200, Currency: "EUR", Status: product.StatusActive}
upd, err := s.Replace(ctx, p.ID, 1, d)
if err != nil || upd.Version != 2 || upd.PriceCents != 1200 {
t.Fatalf("replace: %+v %v", upd, err)
}
// A second client still holding version 1 loses: no lost update.
if _, err := s.Replace(ctx, p.ID, 1, d); !errors.Is(err, product.ErrVersionMismatch) {
t.Fatalf("stale replace: %v", err)
}
}
func TestArchivedIsFrozen(t *testing.T) {
s := newService()
ctx := t.Context()
p, _ := s.Create(ctx, product.Draft{SKU: "OLD", Name: "Old", Currency: "EUR", Status: product.StatusArchived})
_, err := s.Replace(ctx, p.ID, 1, product.Draft{SKU: "OLD", Name: "Old", Currency: "EUR", Status: product.StatusActive})
if !errors.Is(err, product.ErrInvalidTransition) {
t.Fatalf("want ErrInvalidTransition, got %v", err)
}
}
func TestDuplicateSKU(t *testing.T) {
s := newService()
d := product.Draft{SKU: "DUP", Name: "x", Currency: "EUR", Status: product.StatusDraft}
_, _ = s.Create(t.Context(), d)
if _, err := s.Create(t.Context(), d); !errors.Is(err, product.ErrSKUTaken) {
t.Fatalf("want ErrSKUTaken, got %v", err)
}
}Dependency injection via constructors and the run function pattern (Mat Ryer) Must-know
In plain words: Every component gets what it needs through its constructor; nothing reaches for a global. One function, Run, builds the components in order (config, logger, repository, service, HTTP handler, server) and is the only place that knows every concrete type. main calls Run and exits non-zero on error; tests call Run too.
Common misunderstanding: "Go needs a DI container (wire, fx, dig)." For one service, the composition root is twenty lines of plain calls, and the compiler checks it. Containers help when hundreds of components and lifecycles need wiring; they also move errors from compile time to start-up. A second one: "main should do the setup." Then tests cannot run the program, and defer in main does not run on os.Exit. Mat Ryer: "I wish func main() was func main() error", hence func run(ctx context.Context, w io.Writer, args []string) error and a main that only calls it.
Definition: constructor injection means New(deps...) *T (or a Deps struct when the list grows); the run function pattern means the program's entry is a function that takes the operating system as arguments: Mat Ryer's table lists os.Args, os.Stdin, os.Stdout, os.Stderr and os.Getenv as func(string) string. Passing getenv "beats using t.SetEnv ... because you can continue to run your tests in parallel by calling t.Parallel(), which t.SetEnv doesn’t allow". signal.NotifyContext lives inside Run so that its cancel is deferred where it will run (his EDIT: "cancel wouldn’t get called" from main).
1 main() app.Run(context.Background(), os.Args, os.Getenv, os.Stdout)
2 Run ctx := signal.NotifyContext(ctx, SIGINT, SIGTERM); defer cancel()
3 cfg := config.Load(getenv); flags from args
4 repo := memrepo.New() | pgrepo.New(db)
5 svc := service.New(repo, time.Now, newID)
6 h := httpapi.NewServer(Deps{Logger, Products: svc, Cursors, Idempotency, Ready})
7 srv.Serve(ln) until ctx done -> graceful shutdown -> return nil
8 test go app.Run(ctx, args, fakeEnv, pipe); wait /readyz; drive with the clientReal scenario: an end-to-end test that runs the binary's real wiring in-process; swapping the PostgreSQL repository for the in-memory one in a demo with one line; a CLI and an HTTP server sharing the same service constructor; a reviewer spotting a new global because it does not appear in Run.
| Approach | Wiring checked | Testable entry point | When |
|---|---|---|---|
Globals and init() | No | No | Never for services |
Setup in main | Compiler | No (os.Exit, real env) | Throwaway tools |
run(ctx, args, getenv, stdout) error + constructors | Compiler | Yes | Default for services |
Google wire ("a code generation tool", "without runtime state or reflection"; its README: "This project is no longer maintained") | Compiler, generated | Yes | Existing users; prefer plain constructors |
Uber fx ("a dependency injection system for Go") / dig ("A reflection based dependency injection toolkit") | At start-up | Yes, fxtest.New | Many modules with lifecycles |
Fix / how to use it: the Run shown in After is the composition root; app_test.go below starts it, reads the listening address from its JSON log, waits for /readyz like Mat Ryer's waitForReady, drives it through the typed client, then cancels the context and asserts a clean shutdown. Interface-based DI for tests is covered in depth in Mocking with Interfaces & DI.
package app_test
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"testing"
"time"
"academy/rest-api-project/app"
"academy/rest-api-project/client"
"academy/rest-api-project/dto"
)
// start runs the real program, as main would, and returns its base URL once
// /readyz answers 200.
func start(t *testing.T, env map[string]string) (string, context.CancelFunc, <-chan error) {
t.Helper()
ctx, cancel := context.WithCancel(t.Context())
pr, pw := io.Pipe()
done := make(chan error, 1)
go func() {
err := app.Run(ctx, []string{"api", "-addr", "127.0.0.1:0"}, func(k string) string { return env[k] }, pw)
pw.Close()
done <- err
}()
addr := make(chan string, 1)
go func() { // read the log stream; keep draining so logging never blocks
sc := bufio.NewScanner(pr)
for sc.Scan() {
var line struct{ Msg, Addr string }
if json.Unmarshal(sc.Bytes(), &line) == nil && line.Msg == "listening" {
addr <- line.Addr
}
}
}()
var base string
select {
case a := <-addr:
base = "http://" + a
case err := <-done:
t.Fatalf("run exited early: %v", err)
case <-time.After(5 * time.Second):
t.Fatal("server did not start")
}
waitForReady(t, base+"/readyz")
return base, cancel, done
}
func waitForReady(t *testing.T, endpoint string) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
resp, err := http.Get(endpoint)
if err == nil {
resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return
}
}
time.Sleep(20 * time.Millisecond)
}
t.Fatalf("%s never became ready", endpoint)
}
var env = map[string]string{"API_CURSOR_KEY": "0123456789abcdef", "API_SHUTDOWN_TIMEOUT": "2s"}
func TestRunEndToEnd(t *testing.T) {
base, stop, done := start(t, env)
c := &client.Client{BaseURL: base}
ctx := t.Context()
for i := range 5 {
in := dto.ProductWrite{SKU: fmt.Sprintf("SKU-%d", i), Name: "Item", PriceCents: dto.Cents(int64(i * 100)), Currency: "EUR", Status: "active"}
if _, err := c.Create(ctx, fmt.Sprintf("key-%d", i), in); err != nil {
t.Fatal(err)
}
}
// A retry with the same key does not create a sixth product.
if _, err := c.Create(ctx, "key-0", dto.ProductWrite{SKU: "SKU-0", Name: "Item", PriceCents: dto.Cents(0), Currency: "EUR", Status: "active"}); err != nil {
t.Fatal(err)
}
var n int
for p, err := range c.All(ctx, url.Values{"limit": {"2"}, "sort": {"price"}}) {
if err != nil {
t.Fatal(err)
}
if p.PriceCents != int64(n*100) {
t.Fatalf("item %d has price %d", n, p.PriceCents)
}
n++
}
if n != 5 {
t.Fatalf("iterated %d products, want 5", n)
}
var apiErr *client.Error
_, err := c.Create(ctx, "key-x", dto.ProductWrite{SKU: "x"})
if !errors.As(err, &apiErr) || apiErr.Problem.Status != http.StatusUnprocessableEntity {
t.Fatalf("want a 422 problem, got %v", err)
}
stop() // like SIGTERM
select {
case err := <-done:
if err != nil {
t.Fatalf("graceful shutdown returned %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("did not shut down")
}
}
func TestRunRejectsBadConfig(t *testing.T) {
err := app.Run(t.Context(), []string{"api"}, func(string) string { return "" }, io.Discard)
if err == nil {
t.Fatal("want a config error without API_CURSOR_KEY")
}
}Configuration via env Important
In plain words: Everything that differs between your laptop, staging and production (listen address, timeouts, secrets, limits) comes from environment variables, read once at start-up into a typed Config, validated, and passed down like any other dependency.
Common misunderstanding: "Read os.Getenv wherever you need a value." Scattered reads cannot be validated at start-up (the service fails on the first request that needs the value), cannot be listed in one place, and tests that set them with t.Setenv cannot run in parallel. The twelve-factor rule is "Store config in the environment", and its definition of config excludes "how code modules are connected", which stays in code (the composition root).
Definition: config.Load(getenv func(string) string) (Config, error) applies defaults, parses each variable into its Go type (time.ParseDuration, strconv.ParseInt, slog.Level.UnmarshalText), checks ranges and required secrets, and returns all problems joined with errors.Join (Go 1.20) so one failed deploy shows every mistake. Flags parsed from args with flag.NewFlagSet can override env for local runs.
1 API_ADDR=:8080 API_SHUTDOWN_TIMEOUT=soon API_LOG_LEVEL=loud ./api
2 config.Load -> errors.Join(
API_SHUTDOWN_TIMEOUT="soon": want a positive duration like 10s,
API_CURSOR_KEY: required, at least 16 bytes (signs page tokens),
API_LOG_LEVEL="loud": ...)
3 Run returns "config: ..." -> main prints it, exit 1 -> the orchestrator keeps the old versionReal scenario: a Kubernetes Deployment that sets variables from a ConfigMap and a Secret; a missing signing key caught before traffic arrives; a staging environment with a 10 KiB body limit to test 413 handling; a local run with -addr 127.0.0.1:8088.
| Variable | Default | Meaning |
|---|---|---|
API_ADDR | :8080 | Listen address (flag -addr overrides) |
API_SHUTDOWN_TIMEOUT | 10s | Bound for Server.Shutdown |
API_DRAIN_DELAY | 0s | Time between failing /readyz and closing the listener |
API_MAX_BODY_BYTES | 1048576 | MaxBytesReader limit (413 above it) |
API_CURSOR_KEY | required, 16+ bytes | Key material for the page-token cipher (AES-256-GCM key = SHA-256 of it) |
API_LOG_LEVEL | INFO | slog level |
API_REQUIRE_IDEMPOTENCY_KEY | false | 400 for POST without a key |
Fix / how to use it: libraries fill a struct from tags (caarlos0/env: "parse environment variables into structs", env:"HOME"; kelseyhightower/envconfig supports struct tags for "alternate, default, and required" names); the hand-written loader below is short enough that the dependency is not needed. Flags, env and slog setup in general are in CLI Flags, Environment Variables & Logging.
// Package config reads the service configuration from the environment
// (twelve-factor style) through an injected getenv, so tests never touch the
// real process environment.
package config
import (
"errors"
"fmt"
"log/slog"
"strconv"
"time"
)
// Config is everything the binary needs to start. No package-level state.
type Config struct {
Addr string
ShutdownTimeout time.Duration
DrainDelay time.Duration
MaxBodyBytes int64
CursorKey []byte
LogLevel slog.Level
RequireIdemKey bool
}
// Load validates every variable and reports all problems at once.
func Load(getenv func(string) string) (Config, error) {
c := Config{Addr: ":8080", ShutdownTimeout: 10 * time.Second, MaxBodyBytes: 1 << 20}
var errs []error
if v := getenv("API_ADDR"); v != "" {
c.Addr = v
}
if v := getenv("API_SHUTDOWN_TIMEOUT"); v != "" {
d, err := time.ParseDuration(v)
if err != nil || d <= 0 {
errs = append(errs, fmt.Errorf("API_SHUTDOWN_TIMEOUT=%q: want a positive duration like 10s", v))
}
c.ShutdownTimeout = d
}
if v := getenv("API_DRAIN_DELAY"); v != "" {
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
errs = append(errs, fmt.Errorf("API_DRAIN_DELAY=%q: want a duration like 5s", v))
}
c.DrainDelay = d
}
if v := getenv("API_MAX_BODY_BYTES"); v != "" {
n, err := strconv.ParseInt(v, 10, 64)
if err != nil || n <= 0 {
errs = append(errs, fmt.Errorf("API_MAX_BODY_BYTES=%q: want a positive integer", v))
}
c.MaxBodyBytes = n
}
key := getenv("API_CURSOR_KEY")
if len(key) < 16 {
errs = append(errs, errors.New("API_CURSOR_KEY: required, at least 16 bytes (signs page tokens)"))
}
c.CursorKey = []byte(key)
if v := getenv("API_LOG_LEVEL"); v != "" {
if err := c.LogLevel.UnmarshalText([]byte(v)); err != nil {
errs = append(errs, fmt.Errorf("API_LOG_LEVEL=%q: %w", v, err))
}
}
c.RequireIdemKey = getenv("API_REQUIRE_IDEMPOTENCY_KEY") == "true"
return c, errors.Join(errs...)
}Pagination: offset vs cursor/keyset, the Link header and next_cursor Must-know
In plain words: A list endpoint returns one page at a time. Offset pagination says "skip 40, take 20"; keyset (cursor) pagination says "take 20 after the last item you saw". The response carries a next_cursor and a Link header with the URL of the next page; the client follows it until there is none.
Common misunderstanding: "Offset is fine, we only have a few thousand rows." The cost is not only speed. With OFFSET, an insert at the head between two requests shifts every row by one, so the client sees a row twice; a delete makes it skip one. Markus Winand: "the database must still fetch these rows from the disk and bring them in order before it can send the following ones", and "think about what happens if a new row is inserted between fetching two pages". Keyset pagination fixes both, at the price of no "jump to page 37".
Definition: keyset pagination orders by a unique, total key (the sort column plus id as a tie-breaker) and seeks with a row-value comparison, WHERE (price_cents, id) > ($1, $2) ORDER BY price_cents, id LIMIT n+1, which a composite index on (price_cents, id) answers with one index seek per page. The cursor encodes the last row's key. Google AIP-158 sets the rules the snippets follow: page_size 0 means a documented default, larger than the maximum "should coerce down", negative is an error, an empty next_page_token is "the only way to communicate end-of-collection", and tokens "must be opaque (but URL-safe) strings, and must not be user-parseable". AIP-158 also warns: "Base-64 encoding an otherwise-transparent page token is not a sufficient obfuscation mechanism." So the token here is encrypted: AES-256-GCM under a key derived from API_CURSOR_KEY, with a random nonce per token, base64url-encoded. The client cannot read the position or edit it (GCM authenticates the ciphertext, so a changed byte is a 400), two tokens for the same position differ, and the encrypted payload includes a hash of the filter and sort so a token reused with another sort is rejected (400).
1 GET /v1/products?sort=price&limit=2
2 repo.List(limit+1=3) -> SKU-1(100) SKU-2(200) SKU-3(300) 3 > 2: more exist
3 page = first 2; cursor = AES-GCM(nonce, {q: hash("sort=price"), k: {p:200, i:<id of SKU-2>}})
4 200 {"data":[SKU-1,SKU-2],"next_cursor":"KBODNt5Z...","has_more":true}
Link: </v1/products?cursor=KBODNt5Z...&limit=2&sort=price>; rel="next"
5 GET that link -> decrypt -> WHERE (price_cents, id) > (200, '<id of SKU-2>') -> SKU-3, SKU-4
6 same cursor with sort=name -> 400 invalid-query (token bound to its query)Real scenario: an infinite-scroll feed where duplicates are visible to users; a nightly export of millions of rows where OFFSET 900000 takes seconds per page; a partner that syncs "everything since my last cursor"; an admin table that genuinely needs page numbers and a total (offset is acceptable there, with a cap).
| API | Request | Response | Scheme |
|---|---|---|---|
| This chapter | limit, cursor | data, next_cursor, has_more, Link: rel="next" | Keyset, encrypted opaque token |
| Stripe | limit (1 to 100, default 10), starting_after, ending_before | has_more | Object-ID cursor |
| Google AIP-158 | page_size, page_token | next_page_token, optional total_size | Opaque token |
| GitHub REST | per_page (max 100 on most endpoints, coerced down), page, before/after or since | link header with rel="next" | Offset or cursor, by endpoint |
| JSON:API cursor profile | page[size], page[after], page[before] | links + meta | Cursor |
Laravel paginate / simplePaginate / cursorPaginate | ?page= / ?cursor= | links, meta (API Resources) | Offset / offset / keyset |
Offset (LIMIT/OFFSET) | Keyset (cursor) | |
|---|---|---|
| Cost of page N | Grows with N (rows read and discarded) | Constant (index seek) |
| Inserts/deletes between pages | Duplicates or gaps | Stable |
| Jump to page 37 | Yes | No |
| Total count | Natural (COUNT(*), often slow) | Separate, optional |
| Sorting on non-unique columns | Works, unstable ties | Needs id tie-breaker |
| Client can read or tamper | Yes (any offset) | Not with an encrypted, authenticated token |
Fix / how to use it: the pagination package below clamps the limit and encrypts tokens; the keyset SQL is in pgrepo.BuildList and in Mechanics. Index design for keyset queries is in Pagination.
// Package pagination turns a keyset position into an opaque, encrypted and
// authenticated page token and back.
package pagination
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"academy/rest-api-project/product"
)
const (
DefaultLimit = 20
MaxLimit = 100
)
// ErrBadCursor covers every reason a token is rejected: garbled, forged, or
// minted for a different filter/sort than the current request.
var ErrBadCursor = errors.New("invalid cursor")
// Codec encrypts tokens with AES-256-GCM under a key derived from Key, with a
// random nonce per token. Clients can neither read the position (AIP-158:
// tokens "must not be user-parseable"; base64 of JSON is not enough) nor
// forge or edit one (GCM authenticates it).
type Codec struct {
Key []byte
}
type token struct {
Q string `json:"q"` // hash of filter + sort
C product.Cursor `json:"k"`
}
func (c Codec) aead() cipher.AEAD {
k := sha256.Sum256(c.Key)
block, _ := aes.NewCipher(k[:]) // a 32-byte key never fails
g, _ := cipher.NewGCM(block)
return g
}
// Encode returns base64url(nonce || ciphertext).
func (c Codec) Encode(query string, cur product.Cursor) string {
body, _ := json.Marshal(token{Q: queryHash(query), C: cur})
g := c.aead()
nonce := make([]byte, g.NonceSize())
_, _ = rand.Read(nonce)
return base64.RawURLEncoding.EncodeToString(g.Seal(nonce, nonce, body, nil))
}
// Decode authenticates and decrypts the token and checks it belongs to query.
func (c Codec) Decode(query, s string) (product.Cursor, error) {
raw, err := base64.RawURLEncoding.DecodeString(s)
g := c.aead()
if err != nil || len(raw) < g.NonceSize() {
return product.Cursor{}, ErrBadCursor
}
body, err := g.Open(nil, raw[:g.NonceSize()], raw[g.NonceSize():], nil)
if err != nil {
return product.Cursor{}, ErrBadCursor
}
var t token
if err := json.Unmarshal(body, &t); err != nil || t.Q != queryHash(query) {
return product.Cursor{}, ErrBadCursor
}
return t.C, nil
}
func queryHash(q string) string {
sum := sha256.Sum256([]byte(q))
return base64.RawURLEncoding.EncodeToString(sum[:6])
}
// ClampLimit applies the AIP-158 rules: 0 means the default, anything above
// the maximum is coerced down, negatives are an error for the caller.
func ClampLimit(n int) (int, bool) {
switch {
case n < 0:
return 0, false
case n == 0:
return DefaultLimit, true
case n > MaxLimit:
return MaxLimit, true
}
return n, true
}package pagination
import (
"encoding/base64"
"errors"
"slices"
"strings"
"testing"
"academy/rest-api-project/product"
)
func TestRoundTripAndTamper(t *testing.T) {
c := Codec{Key: []byte("test-key")}
cur := product.Cursor{PriceCents: 1999, ID: "prd_42"}
tok := c.Encode("sort=price", cur)
got, err := c.Decode("sort=price", tok)
if err != nil || got != cur {
t.Fatalf("round trip: %+v %v", got, err)
}
if _, err := c.Decode("sort=name", tok); !errors.Is(err, ErrBadCursor) {
t.Fatalf("token reused with another sort must fail, got %v", err)
}
forged := "x" + tok[1:]
if _, err := c.Decode("sort=price", forged); !errors.Is(err, ErrBadCursor) {
t.Fatalf("edited token must fail, got %v", err)
}
}
func TestClampLimit(t *testing.T) {
for in, want := range map[int]int{0: DefaultLimit, 7: 7, 500: MaxLimit} {
if got, ok := ClampLimit(in); !ok || got != want {
t.Errorf("ClampLimit(%d) = %d, %v", in, got, ok)
}
}
if _, ok := ClampLimit(-1); ok {
t.Error("negative limit must be rejected")
}
}
// TestOffsetDriftVsKeyset shows why the API pages by keyset: a row inserted
// at the head between two requests duplicates a row under OFFSET and is
// harmless under "WHERE id < last_seen".
func TestOffsetDriftVsKeyset(t *testing.T) {
rows := []int{9, 8, 7, 6, 5, 4} // newest first, like ORDER BY id DESC
offsetPage := func(rows []int, offset, limit int) []int { return rows[offset : offset+limit] }
keysetPage := func(rows []int, after, limit int) []int {
var out []int
for _, r := range rows {
if r < after && len(out) < limit {
out = append(out, r)
}
}
return out
}
p1 := offsetPage(rows, 0, 3) // 9 8 7
k1 := keysetPage(rows, 1<<31, 3)
rows = append([]int{10}, rows...) // a new row arrives
p2 := offsetPage(rows, 3, 3) // 7 6 5: 7 again
k2 := keysetPage(rows, k1[len(k1)-1], 3) // 6 5 4
if !slices.Contains(p1, p2[0]) {
t.Fatalf("expected offset drift, got %v then %v", p1, p2)
}
if !slices.Equal(k2, []int{6, 5, 4}) {
t.Fatalf("keyset page 2 = %v", k2)
}
}
// AIP-158: tokens must not be user-parseable; base64 of JSON is not enough.
func TestTokenIsOpaque(t *testing.T) {
c := Codec{Key: []byte("test-key-test-key")}
cur := product.Cursor{PriceCents: 1999, ID: "prd_42"}
a, b := c.Encode("sort=price", cur), c.Encode("sort=price", cur)
if a == b {
t.Fatal("two tokens for the same position must differ (random nonce)")
}
for _, part := range strings.Split(a, ".") {
raw, _ := base64.RawURLEncoding.DecodeString(part)
if strings.Contains(string(raw), "prd_42") || strings.Contains(string(raw), "1999") {
t.Fatalf("token reveals the position: %q", raw)
}
}
if got, err := c.Decode("sort=price", b); err != nil || got != cur {
t.Fatalf("round trip: %+v %v", got, err)
}
}Filtering and sorting Important
In plain words: Filters narrow the collection (?status=active&min_price=500), sorting orders it (?sort=-price for descending). Both are query parameters, both are validated against an allow-list, and both are part of what a cursor is valid for.
Common misunderstanding: "Pass the sort parameter into ORDER BY." That is SQL injection (?sort=name;DROP TABLE products) and also lets clients sort by unindexed columns, which turns one request into a full table scan. The second mistake is accepting a free-form filter language without a budget: Google AIP-160 does define a filter grammar, but also warns that filtering requirements "evolve frequently".
Definition: each filter is a named, typed parameter (status must be a known status, prices are non-negative integers in cents); sort is one of an allow-listed set of fields with an optional - prefix, mapped to a column name by a fixed map (sortColumns in pgrepo), with id always appended as a tie-breaker. Every allowed sort has an index on (column, id). Unknown parameters are ignored here; stricter APIs reject them with 400.
1 ?status=active&min_price=500&sort=-price&limit=20
2 parseList: status ok · min_price=500 · sort -> (SortPrice, desc) · limit 20
3 fingerprint = "max_price=&min_price=500&sort=-price&status=active" cursor binds to it
4 SQL: WHERE status = $1 AND price_cents >= $2 ORDER BY price_cents DESC, id DESC LIMIT $3
5 ?sort=colour -> 400 "sort: must be one of created_at, price, name, optionally prefixed with -"Real scenario: a storefront filtering by category and price range; an admin search by status sorted by last update; a reporting client that must not be able to sort by an unindexed text column; a partner API that needs updated_at > X to sync changes.
| Style | Example | Pros | Cons |
|---|---|---|---|
| Named parameters (this chapter) | ?status=active&min_price=500 | Typed, documented in OpenAPI, easy to index | One parameter per filter |
| Bracket operators | ?price[gte]=500 | Many operators | Harder to document and validate |
| Filter expression (AIP-160) | filter=status = "ACTIVE" AND price > 500 | Expressive | Parser, cost control |
JSON:API filter[...] | ?filter[status]=active | Spec-defined family | Semantics left to the server |
| Sort | ?sort=-price,name | Familiar (JSON:API uses - for descending) | Each combination needs an index |
Fix / how to use it: parseList in handlers.go is the whole parser; the SQL builder test proves the allow-list (TestUnknownSortFallsBackToAllowList).
package pgrepo
import (
"errors"
"fmt"
"slices"
"testing"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
var _ service.Repository = (*Repo)(nil)
func TestBuildListKeysetDesc(t *testing.T) {
minPrice := int64(500)
q := product.ListQuery{
Status: product.StatusActive, MinPrice: &minPrice,
Sort: product.SortPrice, Desc: true, Limit: 20,
After: &product.Cursor{PriceCents: 1999, ID: "prd_42"},
}
sql, args := BuildList(q)
want := "SELECT " + columns + " FROM products WHERE status = $1 AND price_cents >= $2" +
" AND (price_cents, id) < ($3, $4) ORDER BY price_cents DESC, id DESC LIMIT $5"
if sql != want {
t.Fatalf("sql:\n%s\nwant:\n%s", sql, want)
}
if !slices.Equal(args, []any{"active", int64(500), int64(1999), "prd_42", 21}) {
t.Fatalf("args %v", args)
}
}
func TestUnknownSortFallsBackToAllowList(t *testing.T) {
sql, _ := BuildList(product.ListQuery{Sort: "name; DROP TABLE products", Limit: 1})
want := "SELECT " + columns + " FROM products ORDER BY created_at ASC, id ASC LIMIT $1"
if sql != want {
t.Fatalf("got %s", sql)
}
}
type pgErr string
func (e pgErr) Error() string { return "pg: " + string(e) }
func (e pgErr) SQLState() string { return string(e) }
func TestMapUniqueViolation(t *testing.T) {
err := fmt.Errorf("insert: %w", pgErr("23505"))
if !errors.Is(mapErr(err), product.ErrSKUTaken) {
t.Fatal("23505 must map to ErrSKUTaken")
}
if errors.Is(mapErr(pgErr("23503")), product.ErrSKUTaken) {
t.Fatal("other states pass through")
}
}Partial updates: PATCH and JSON Merge Patch Must-know
In plain words: PUT sends the whole writable representation; PATCH sends only what changes. With JSON Merge Patch (Content-Type: application/merge-patch+json) the patch looks like the document: members present are set, members set to null are removed, members absent are left alone.
Common misunderstanding: "Decode the PATCH body into the same struct and copy the non-zero fields." Then a client cannot set a price to 0, clear a list or remove an optional field, because "absent", null and the zero value all look the same in a Go struct. Pointer fields help for scalars but not for nested objects. Applying RFC 7396 to the JSON representation, then decoding and validating the result like a PUT, has none of these holes.
Definition: RFC 5789 defines PATCH as applying "a set of changes described in the request entity"; it is not idempotent by definition. RFC 7396's algorithm: if the patch is not an object, it replaces the target; otherwise, for each member, null deletes the target member and any other value is merged recursively. Arrays are replaced, not merged. The format "is not appropriate for all JSON syntaxes": you cannot set a member to null or edit one array element; for that use JSON Patch (RFC 6902, application/json-patch+json, operations add, remove, replace, move, copy, test). The snippet passes all fifteen test cases of RFC 7396 Appendix A.
1 stored {"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}
2 PATCH If-Match: "v1" {"price_cents":1200,"status":"active","tags":null}
3 merged {"sku":"MUG-1","name":"Mug","price_cents":1200,"currency":"EUR","status":"active"}
4 decode DisallowUnknownFields into ProductWrite; Valid(ctx) -> ok
5 svc.Replace version 1 -> 2; 200, ETag "v2", "tags": []
6 PATCH {"id":"prd_999"} -> merged doc has unknown member "id" -> 400 (read-only fields cannot be patched)Real scenario: a mobile app that edits one field of a large profile; an admin UI that clears an optional discount; a sync client that sends only changed fields to save bandwidth; a settings page whose nested notifications object is edited one switch at a time.
| Technique | Media type | Can set null | Can edit one array element | Idempotent | Complexity |
|---|---|---|---|---|---|
| PUT full representation | application/json | Yes | By sending the whole array | Yes | Lowest |
| JSON Merge Patch (RFC 7396) | application/merge-patch+json | No (null means delete) | No (arrays are replaced) | Yes in practice for the same patch | Low |
| JSON Patch (RFC 6902) | application/json-patch+json | Yes | Yes (/tags/2) | Not in general (add to an array) | Medium |
| Struct with pointer fields | application/json | No | No | Depends | Grows with every field |
Field mask (AIP-134 update_mask) | gRPC/JSON | Yes | Yes | Yes | Medium |
Fix / how to use it: a library such as evanphx/json-patch implements both RFC 7396 and RFC 6902; the 40-line implementation below is enough for merge patch and is tested against the RFC's own table.
// Package mergepatch implements RFC 7396 JSON Merge Patch on decoded JSON
// values (map[string]any, []any, string, float64, bool, nil).
package mergepatch
import (
"encoding/json"
"fmt"
)
// MediaType is the content type a PATCH request must declare.
const MediaType = "application/merge-patch+json"
// Apply is the algorithm of RFC 7396 section 2, line for line: a non-object
// patch replaces the target; an object patch is merged member by member, and
// a null member deletes that member from the target.
func Apply(target, patch any) any {
p, ok := patch.(map[string]any)
if !ok {
return patch
}
t, ok := target.(map[string]any)
if !ok {
t = map[string]any{}
}
for name, value := range p {
if value == nil {
delete(t, name)
continue
}
t[name] = Apply(t[name], value)
}
return t
}
// ApplyJSON patches a JSON document and returns the new document.
func ApplyJSON(doc, patch []byte) ([]byte, error) {
var t, p any
if err := json.Unmarshal(doc, &t); err != nil {
return nil, fmt.Errorf("target: %w", err)
}
if err := json.Unmarshal(patch, &p); err != nil {
return nil, fmt.Errorf("patch: %w", err)
}
return json.Marshal(Apply(t, p))
}package mergepatch
import (
"encoding/json"
"reflect"
"testing"
)
// The example test cases of RFC 7396 Appendix A, verbatim.
var appendixA = []struct{ original, patch, result string }{
{`{"a":"b"}`, `{"a":"c"}`, `{"a":"c"}`},
{`{"a":"b"}`, `{"b":"c"}`, `{"a":"b","b":"c"}`},
{`{"a":"b"}`, `{"a":null}`, `{}`},
{`{"a":"b","b":"c"}`, `{"a":null}`, `{"b":"c"}`},
{`{"a":["b"]}`, `{"a":"c"}`, `{"a":"c"}`},
{`{"a":"c"}`, `{"a":["b"]}`, `{"a":["b"]}`},
{`{"a":{"b":"c"}}`, `{"a":{"b":"d","c":null}}`, `{"a":{"b":"d"}}`},
{`{"a":[{"b":"c"}]}`, `{"a":[1]}`, `{"a":[1]}`},
{`["a","b"]`, `["c","d"]`, `["c","d"]`},
{`{"a":"b"}`, `["c"]`, `["c"]`},
{`{"a":"foo"}`, `null`, `null`},
{`{"a":"foo"}`, `"bar"`, `"bar"`},
{`{"e":null}`, `{"a":1}`, `{"e":null,"a":1}`},
{`[1,2]`, `{"a":"b","c":null}`, `{"a":"b"}`},
{`{}`, `{"a":{"bb":{"ccc":null}}}`, `{"a":{"bb":{}}}`},
}
func TestRFC7396AppendixA(t *testing.T) {
for _, c := range appendixA {
got, err := ApplyJSON([]byte(c.original), []byte(c.patch))
if err != nil {
t.Fatal(err)
}
var g, w any
_ = json.Unmarshal(got, &g)
_ = json.Unmarshal([]byte(c.result), &w)
if !reflect.DeepEqual(g, w) {
t.Errorf("%s + %s = %s, want %s", c.original, c.patch, got, c.result)
}
}
}ETag and If-Match: optimistic concurrency over HTTP Must-know
In plain words: Every read returns an ETag (here "v3", the aggregate's version). A client that wants to change the resource sends that value back in If-Match. If someone else changed it in between, the server refuses with 412 instead of silently overwriting their work.
Common misunderstanding: "Our database has transactions, so concurrent edits are safe." A transaction protects one request; a lost update spans two requests by two people with minutes between read and write. Only a version check at write time ("update where version = what you saw") prevents it. A second one: "ETags are only for caching." If-None-Match is for caching (304); If-Match is for safe writes.
Definition: RFC 9110: an origin server that evaluates If-Match "MUST NOT perform the requested method if the condition evaluates to false" and may answer 412 (Precondition Failed); If-Match uses strong comparison, so a weak tag (W/"...") never matches. RFC 6585 adds 428 (Precondition Required): "Its typical use is to avoid the "lost update" problem". The chapter requires If-Match on PUT, PATCH and DELETE, accepts * as "whatever is current", compares every listed tag literally against the current tag ("v2"; the server never parses a number out of a client's tag, so "v02" or "v-1" do not match), and If-None-Match on GET uses the weak comparison RFC 9110 requires ("A recipient MUST use the weak comparison function when comparing entity tags for If-None-Match"), so W/"v2" and * give 304. It then enforces the version in the same UPDATE ... WHERE version = $9 that writes the row, so even two requests racing past the handler cannot both win. Google AIP-154 describes the same mechanism with an etag field in the resource for gRPC APIs.
client A API client B
1 GET -> ETag "v1" GET -> ETag "v1"
2 PATCH If-Match "v1" {price} ─▶ version 1 == 1 -> v2
3 ◀─ 200 ETag "v2"
4 version 2 != 1 ◀─────────── PATCH If-Match "v1" {name}
5 412 problem stale-version ─▶ re-GET v2, re-apply, retry
6 PUT without If-Match ─▶ 428 if-match-requiredReal scenario: two support agents editing the same customer; a price change from an admin UI racing with a bulk import; a mobile client offline for an hour that syncs a stale edit; a CMS where two editors publish the same page.
| Mechanism | Where the version lives | Conflict answer | Notes |
|---|---|---|---|
ETag + If-Match (this chapter) | Header, from version column | 412; missing header 428 | Works with any HTTP client and cache |
| Version field in the body | JSON ("version": 3) | 409 or 412 | Easy for clients, invisible to HTTP tooling |
| Google AIP-154 | etag field in the resource | ABORTED (changed from FAILED_PRECONDITION in 2021) | gRPC-first APIs |
| Last write wins | Nowhere | None | Acceptable only for single-writer data |
Pessimistic lock (SELECT ... FOR UPDATE) | Database, one request | Wait | Does not span two HTTP requests |
Fix / how to use it: the If-Match parser is below; the database side of version columns is in Optimistic vs Pessimistic Locking.
package httpapi
import (
"net/http"
"strconv"
"strings"
"academy/rest-api-project/problem"
)
// etag derives a strong entity tag from the aggregate version. Clients treat
// it as opaque; the server only ever compares it as a string.
func etag(version int64) string { return `"v` + strconv.FormatInt(version, 10) + `"` }
// condition is a parsed If-Match or If-None-Match field: "*" or a list of
// entity-tags, kept literally (W/ prefix included).
type condition struct {
any bool
tags []string
}
// parseCondition splits a field value into entity-tags (RFC 9110 8.8.3).
// Anything that is not a well-formed tag is kept as-is and never matches.
func parseCondition(h string) condition {
h = strings.TrimSpace(h)
if h == "*" {
return condition{any: true}
}
var c condition
for len(h) > 0 {
h = strings.TrimLeft(h, " \t,")
if h == "" {
break
}
start := 0
if strings.HasPrefix(h, "W/") {
start = 2
}
if len(h) > start && h[start] == '"' {
if end := strings.IndexByte(h[start+1:], '"'); end >= 0 {
n := start + 1 + end + 1
c.tags = append(c.tags, h[:n])
h = h[n:]
continue
}
}
junk, rest, _ := strings.Cut(h, ",") // malformed member
c.tags = append(c.tags, strings.TrimSpace(junk))
h = rest
}
return c
}
// strongMatch is the If-Match test: both tags strong and identical.
func (c condition) strongMatch(current string) bool {
if c.any {
return true
}
for _, t := range c.tags {
if !strings.HasPrefix(t, "W/") && t == current {
return true
}
}
return false
}
// weakMatch is the If-None-Match test: opaque parts equal, W/ ignored.
func (c condition) weakMatch(current string) bool {
if c.any {
return true
}
cur := strings.TrimPrefix(current, "W/")
for _, t := range c.tags {
if strings.TrimPrefix(t, "W/") == cur {
return true
}
}
return false
}
// requireIfMatch makes PUT, PATCH and DELETE conditional: no header is 428
// Precondition Required (RFC 6585). Matching happens later, against the
// current representation's tag.
func requireIfMatch(r *http.Request) (condition, *problem.Problem) {
h := strings.TrimSpace(r.Header.Get("If-Match"))
if h == "" {
return condition{}, problem.New(http.StatusPreconditionRequired, "if-match-required", "If-Match header is required",
"send the ETag from your last GET to avoid overwriting someone else's change")
}
return parseCondition(h), nil
}
func staleProblem() *problem.Problem {
return problem.New(http.StatusPreconditionFailed, "stale-version", "Resource changed since you read it",
"GET it again and retry with the new ETag in If-Match")
}Idempotency key for POST Must-know
In plain words: POST creates something new each time. If the network drops the response, the client cannot know whether the product (or payment) was created. With an Idempotency-Key header, the client sends the same key on every retry, and the server returns the first response instead of doing the work again.
Common misunderstanding: "A unique constraint is enough." It stops the duplicate row but turns a safe retry into a 409 the client must interpret, and it does not exist for operations without a natural key (a payment, an email). Another one: "Store the key and skip duplicates." The server must also store the response to replay it, detect a key reused with a different body, and handle a retry that arrives while the first request is still running.
Definition: the IETF draft says the key "MUST be unique and MUST NOT be reused with another request with a different request payload"; a server "MAY compute a fingerprint of the request payload". Its error cases: missing key on an operation that requires it, 400; key reused with a different payload, 422; retry "while the original request is still being processed", 409. Stripe: "Stripe saves the status code and body of the first request made with a given idempotency key"; "you can remove keys from the system automatically after they’re at least 24 hours old"; keys are "up to 255 characters long"; "Don’t send idempotency keys in GET and DELETE requests because it has no effect". The snippet scopes keys by method and path, applies the body size limit itself (it must read the body to fingerprint it, before the handler's own MaxBytesReader runs), fingerprints the body with SHA-256, releases the key if the handler panics (otherwise retries would get 409 until the TTL), starts its buffer with the outer response headers so problem bodies keep their request_id, stores only final non-5xx responses (Stripe's v1 replays even 500s; storing them or not is a design choice) and marks replays with an Idempotent-Replayed: true header of its own.
1 POST Idempotency-Key "8e03..." body B -> new: reserve (in flight) -> handler -> 201 -> store
2 POST same key, same B (retry) -> done: replay 201, same Location, Idempotent-Replayed: true
3 POST same key while 1 still runs -> in flight: 409 idempotency-key-in-flight
4 POST same key, body B' -> fingerprint differs: 422 idempotency-key-reused
5 first attempt answered 503 -> not stored; the retry runs the handler again
6 24 h later -> expired; the key is new againReal scenario: a checkout button pressed twice; a mobile client that retries after a timeout on a flaky network; a webhook consumer that re-delivers; a job runner that restarts a half-finished batch of creates.
| Decision | This chapter | Stripe API v1 | IETF draft |
|---|---|---|---|
| Header | Idempotency-Key (quoted or bare) | Idempotency-Key | Idempotency-Key, a Structured Field string |
| Fingerprint | SHA-256 of the body | Compares parameters | Optional, document it |
| Reused with other payload | 422 | Error | 422 |
| Concurrent retry | 409 | Error (not saved) | 409 |
| 5xx stored | No | Yes | Not specified |
| Retention | 24 h (NewStore(ttl)) | At least 24 h | Not specified |
| Store | In memory (one instance) | Their infrastructure | Not specified |
Fix / how to use it: on more than one instance, the store must be shared and the reservation atomic: an idempotency_keys table with a primary key on the scoped key (INSERT ... ON CONFLICT DO NOTHING), or Redis SET key value NX EX 86400. For writes that change several tables, write the stored response in the same transaction as the business change. The cross-cutting design is in API Idempotency.
// Package idempotency makes POST safe to retry: the first response for an
// Idempotency-Key is stored and replayed for every retry with the same key
// and the same body (draft-ietf-httpapi-idempotency-key-header).
package idempotency
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"academy/rest-api-project/problem"
)
// Header is the request header name from the IETF draft (and Stripe).
const Header = "Idempotency-Key"
// ReplayedHeader marks a replayed response; the name is this API's choice.
const ReplayedHeader = "Idempotent-Replayed"
type record struct {
fingerprint string
done bool
status int
header http.Header
body []byte
at time.Time
}
// Store keeps records in memory. A multi-instance deployment needs a shared
// store (a table with a unique key, or Redis SET NX) with the same states.
type Store struct {
mu sync.Mutex
recs map[string]*record
ttl time.Duration
now func() time.Time
}
// NewStore keeps records for ttl (Stripe prunes keys after 24 hours).
func NewStore(ttl time.Duration, now func() time.Time) *Store {
return &Store{recs: map[string]*record{}, ttl: ttl, now: now}
}
// Middleware wraps POST handlers. required=true rejects a POST without a key.
// The body is read here (to fingerprint it), so the size limit applies here.
func (s *Store) Middleware(required bool, maxBytes int64) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := strings.Trim(r.Header.Get(Header), `"`) // the draft sends a quoted sf-string
if r.Method != http.MethodPost || key == "" {
if required && r.Method == http.MethodPost {
problem.Write(w, r, problem.New(http.StatusBadRequest, "idempotency-key-missing",
"Idempotency-Key header is required", "send a unique key (a UUID) per logical operation"))
return
}
next.ServeHTTP(w, r)
return
}
if maxBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, maxBytes)
}
body, err := io.ReadAll(r.Body)
var tooBig *http.MaxBytesError
switch {
case errors.As(err, &tooBig):
problem.Write(w, r, problem.New(http.StatusRequestEntityTooLarge, "body-too-large", "Request body too large",
fmt.Sprintf("limit is %d bytes", tooBig.Limit)))
return
case err != nil:
problem.Write(w, r, problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "could not read body"))
return
}
sum := sha256.Sum256(body)
fp := hex.EncodeToString(sum[:])
scope := r.Method + " " + r.URL.Path + " " + key
rec, fresh := s.begin(scope, fp)
switch {
case !fresh && rec.fingerprint != fp:
problem.Write(w, r, problem.New(http.StatusUnprocessableEntity, "idempotency-key-reused",
"Idempotency-Key reused with a different request body", ""))
return
case !fresh && !rec.done:
problem.Write(w, r, problem.New(http.StatusConflict, "idempotency-key-in-flight",
"A request with this Idempotency-Key is still being processed", "retry later"))
return
case !fresh:
replay(w, rec)
return
}
r.Body = io.NopCloser(bytes.NewReader(body))
cw := &captureWriter{header: w.Header().Clone(), status: http.StatusOK} // keeps X-Request-ID
defer func() {
if v := recover(); v != nil {
s.abandon(scope) // a panic must not leave the key "in flight" until the TTL
panic(v)
}
}()
next.ServeHTTP(cw, r)
s.finish(scope, cw)
if rec, ok := w.(interface{ SetError(error) }); ok && cw.err != nil {
rec.SetError(cw.err) // pass the 5xx cause on to the access log
}
copyResponse(w, cw.header, cw.status, cw.buf.Bytes())
})
}
}
// begin returns the live record for scope, or reserves a new in-flight one.
func (s *Store) begin(scope, fp string) (rec record, fresh bool) {
s.mu.Lock()
defer s.mu.Unlock()
if r, ok := s.recs[scope]; ok && s.now().Sub(r.at) < s.ttl {
return *r, false
}
s.recs[scope] = &record{fingerprint: fp, at: s.now()}
return record{}, true
}
// finish stores a final response. 5xx are not stored, so the client may
// retry them (Stripe's v1 API stores even 500s; this is a design choice).
func (s *Store) finish(scope string, cw *captureWriter) {
s.mu.Lock()
defer s.mu.Unlock()
if cw.status >= 500 {
delete(s.recs, scope)
return
}
r := s.recs[scope]
h := cw.header.Clone()
h.Del("X-Request-ID") // a replay carries the retry's own request id header
r.done, r.status, r.header, r.body = true, cw.status, h, bytes.Clone(cw.buf.Bytes())
}
func (s *Store) abandon(scope string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.recs, scope)
}
func replay(w http.ResponseWriter, rec record) {
h := rec.header.Clone()
h.Set(ReplayedHeader, "true")
copyResponse(w, h, rec.status, rec.body)
}
func copyResponse(w http.ResponseWriter, h http.Header, status int, body []byte) {
for k, v := range h {
w.Header()[k] = v
}
w.WriteHeader(status)
_, _ = w.Write(body)
}
// captureWriter buffers the inner handler's response so it can be stored.
type captureWriter struct {
header http.Header
status int
wrote bool
buf bytes.Buffer
err error
}
// SetError keeps the internal cause that writeError attaches.
func (c *captureWriter) SetError(err error) { c.err = err }
func (c *captureWriter) Header() http.Header { return c.header }
func (c *captureWriter) WriteHeader(code int) {
if !c.wrote {
c.status, c.wrote = code, true
}
}
func (c *captureWriter) Write(p []byte) (int, error) {
c.wrote = true
return c.buf.Write(p)
}package idempotency
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func setup(handler http.HandlerFunc) (http.Handler, *atomic.Int32) {
var calls atomic.Int32
s := NewStore(24*time.Hour, time.Now)
h := s.Middleware(true, 1<<10)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
handler(w, r)
}))
return h, &calls
}
func post(h http.Handler, key, body string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/v1/products", strings.NewReader(body))
if key != "" {
req.Header.Set(Header, key)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
return rec
}
func TestRetryIsReplayed(t *testing.T) {
h, calls := setup(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", "/v1/products/prd_1")
w.WriteHeader(http.StatusCreated)
fmt.Fprint(w, `{"id":"prd_1"}`)
})
first := post(h, `"8e03978e-40d5-43e8-bc93-6894a57f9324"`, `{"sku":"A"}`)
retry := post(h, `"8e03978e-40d5-43e8-bc93-6894a57f9324"`, `{"sku":"A"}`)
if first.Code != 201 || retry.Code != 201 || retry.Body.String() != first.Body.String() {
t.Fatalf("first %d %q, retry %d %q", first.Code, first.Body, retry.Code, retry.Body)
}
if retry.Header().Get(ReplayedHeader) != "true" || retry.Header().Get("Location") == "" {
t.Fatalf("replay headers %v", retry.Header())
}
if calls.Load() != 1 {
t.Fatalf("handler ran %d times, want 1", calls.Load())
}
}
func TestStatusCodesFromTheDraft(t *testing.T) {
started, release := make(chan struct{}), make(chan struct{})
h, _ := setup(func(w http.ResponseWriter, r *http.Request) {
close(started) // only the first request for k1 reaches the handler
<-release
w.WriteHeader(http.StatusCreated)
})
if got := post(h, "", `{}`).Code; got != http.StatusBadRequest {
t.Errorf("missing key: %d, want 400", got)
}
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); post(h, "k1", `{"sku":"A"}`) }()
<-started
if got := post(h, "k1", `{"sku":"A"}`).Code; got != http.StatusConflict {
t.Errorf("retry while the first is running: %d, want 409", got)
}
close(release)
wg.Wait()
if got := post(h, "k1", `{"sku":"B"}`).Code; got != http.StatusUnprocessableEntity {
t.Errorf("same key, other body: %d, want 422", got)
}
}
func TestServerErrorsAreNotStored(t *testing.T) {
fail := true
h, calls := setup(func(w http.ResponseWriter, r *http.Request) {
if fail {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusCreated)
})
if post(h, "k2", `{}`).Code != 503 {
t.Fatal("first attempt should fail")
}
fail = false
if got := post(h, "k2", `{}`).Code; got != 201 || calls.Load() != 2 {
t.Fatalf("retry after 5xx: %d, calls %d", got, calls.Load())
}
}
func TestBodyLimitAppliesBeforeFingerprinting(t *testing.T) {
h, calls := setup(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusCreated) })
if got := post(h, "big", strings.Repeat("x", 2<<10)).Code; got != http.StatusRequestEntityTooLarge {
t.Fatalf("oversized body: %d, want 413", got)
}
if calls.Load() != 0 {
t.Fatal("handler must not run")
}
}
func TestPanicReleasesTheKey(t *testing.T) {
boom := true
h, _ := setup(func(w http.ResponseWriter, r *http.Request) {
if boom {
panic("handler bug")
}
w.WriteHeader(http.StatusCreated)
})
func() {
defer func() { _ = recover() }()
post(h, "k3", `{}`)
}()
boom = false
if got := post(h, "k3", `{}`).Code; got != http.StatusCreated {
t.Fatalf("retry after a panic: %d, want 201 (not 409 in flight)", got)
}
}Versioning: /v1 Important
In plain words: The URL starts with /v1. Additive changes (a new optional field, a new endpoint) ship inside v1; breaking changes (renaming a field, changing a type, removing an endpoint) ship as /v2, served next to /v1 until clients have moved.
Common misunderstanding: "Bump the version on every release." Versions are for breaking changes only; Google AIP-185 says APIs "must provide a major version number" and that "Google APIs use v1, not v1.0, v1.1, or v1.4.2", with minor changes "updated in place". The opposite mistake is no version at all, which makes the first breaking change a flag day for every client.
Definition: a major version identifies an incompatible contract. Path versioning (/v1) is visible, cacheable and trivial to route with ServeMux ("GET /v2/products" is just another pattern); header versioning moves the version into a request header: Stripe names versions by release date plus a codename (the reference lists 2026-11-18.endive as current; since 2024-09-30.acacia it releases monthly versions without breaking changes and a new major release twice a year) and lets curl requests override the account's default version with the Stripe-Version header; GitHub's REST API uses X-GitHub-Api-Version and "Requests without the X-GitHub-Api-Version header will default to use the 2022-11-28 version". A new major version should not depend on the old one (AIP-185) but usually shares the service layer.
1 v1 live: GET /v1/products -> dto.ProductView{price_cents}
2 need: price as {"amount":"9.00","currency":"EUR"} breaking
3 add GET /v2/products -> dtov2.ProductView{price{...}} ; same service.List
4 v1 responses: Deprecation (RFC 9745) and Sunset (RFC 8594) headers, docs say "v1 ends 2027-06-30"
5 traffic on /v1 falls to 0 (metrics by r.Pattern) -> remove v1 routes and DTOsReal scenario: a public API with mobile apps that update slowly; an internal API where all clients deploy together (versioning may be unnecessary); a partner integration pinned to a dated version; a v2 that changes pagination from page numbers to cursors.
| Strategy | Example | Routing in Go | Caching | Used by |
|---|---|---|---|---|
| Path | /v1/products | One pattern per version | Natural | Google APIs, this chapter |
| Header (date) | Stripe-Version: 2026-11-18.endive | Middleware picks DTOs | Needs Vary | Stripe |
| Header (named) | X-GitHub-Api-Version: 2022-11-28 | Middleware | Needs Vary | GitHub REST |
| Media type | Accept: application/vnd.acme.v2+json | Content negotiation | Needs Vary | Some hypermedia APIs |
| No version, additive only | Nothing | Natural | Internal APIs with lockstep deploys |
Fix / how to use it: keep versions at the edge (routes and DTOs), never in the service; the strategy trade-offs are in API Versioning. The test TestMuxErrorsBecomeProblems shows an unknown /v2/products returning a 404 problem.
OpenAPI 3.1: the contract, and a test that keeps it true Must-know
In plain words: openapi.json describes every operation: paths, parameters, request and response schemas, headers and error responses. Tools read it to render docs, generate clients and validate traffic. A test compares it with the routes the server actually registers, so it cannot drift.
Common misunderstanding: "OpenAPI is documentation." It is a machine-readable contract; documentation is one of its outputs. The spec's own definition: it "defines a standard, language-agnostic interface to HTTP APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code". A second one: "3.0 and 3.1 are the same." 3.1 aligned the Schema Object with JSON Schema 2020-12 (oapi-codegen's README calls type: [T, "null"] the 3.1 idiom for nullability; 3.0 used nullable: true) and added top-level webhooks; tools that only speak 3.0 may reject a 3.1 document.
Definition: the document has openapi: "3.1.0", info, servers, paths (each with operations keyed by lowercase method), and components (schemas, parameters, responses). This chapter's document reuses one Problem response for every error status, marks server-set fields readOnly, declares additionalProperties: false on ProductWrite (matching DisallowUnknownFields), defines the response Product as its own object rather than allOf: [ProductWrite, ...] (the spec says allOf branches "are validated independently", so the write schema's additionalProperties: false would reject id and version), sets servers to / so the docs page calls the origin that served it, and documents If-Match, Idempotency-Key and Link. It is embedded with //go:embed and served at /openapi.json. TestContractMatchesRoutes turns every paths entry into "METHOD /path" and compares with httpapi.Routes(); Go 1.22 patterns and OpenAPI paths use the same {id} syntax, so no translation is needed. TestResponsesMatchSchemas validates real response bodies (a product, a list, two problems) against the component schemas with a forty-line checker for type, enum, required, properties, additionalProperties, items, allOf and $ref; it is what caught the allOf mistake in the first version of this document.
1 developer adds {"GET /v1/products/{id}/history", handleHistory(...), true} to routes
2 go test ./httpapi
3 --- FAIL: TestContractMatchesRoutes
spec [DELETE /v1/products/{id} GET /v1/products ... ]
routed [DELETE /v1/products/{id} GET /v1/products GET /v1/products/{id}/history ...]
4 developer documents the operation in openapi.json -> test passes -> docs and clients see itReal scenario: a frontend team generating a TypeScript client on every merge; a partner portal rendering the reference; an API gateway importing the spec for routing and validation; a breaking-change check in CI comparing the spec with the previous release (oasdiff and similar tools).
| Version | Released | Schema dialect | Notable |
|---|---|---|---|
| Swagger 2.0 | 2014-09-08 | JSON Schema subset | swaggo/swag v1 output; definitions, basePath |
| OpenAPI 3.0.x | 3.0.0 on 2017-07-26 | Extended subset, nullable | components, requestBody, servers |
| OpenAPI 3.1.0 | 2021-02-15 | JSON Schema 2020-12 superset | webhooks, type arrays for nullability |
| OpenAPI 3.1.1 | Patch release | Same | Clarifications |
| OpenAPI 3.2.x | Latest line (3.2.1) | Same | query operation, additionalOperations (per oapi-codegen's README) |
Fix / how to use it: keep the document next to the code, embed it, serve it, and test it against the routes; add request validation from the document (kin-openapi's openapi3filter) if you want the spec to be enforced at runtime too.
{
"openapi": "3.1.0",
"info": {
"title": "Products API",
"version": "1.0.0",
"description": "Chapter example: CRUD, merge-patch, ETag/If-Match, Idempotency-Key, keyset pagination, RFC 9457 errors."
},
"servers": [{ "url": "/", "description": "Same origin as this document; tools may override (for example https://api.example.test)" }],
"paths": {
"/v1/products": {
"get": {
"operationId": "listProducts",
"summary": "List products (filter, sort, cursor pagination)",
"parameters": [
{ "name": "limit", "in": "query", "schema": { "type": "integer", "minimum": 0, "maximum": 100, "default": 20 } },
{ "name": "cursor", "in": "query", "description": "Opaque token from next_cursor", "schema": { "type": "string" } },
{ "name": "status", "in": "query", "schema": { "$ref": "#/components/schemas/Status" } },
{ "name": "min_price", "in": "query", "schema": { "type": "integer", "minimum": 0 } },
{ "name": "max_price", "in": "query", "schema": { "type": "integer", "minimum": 0 } },
{ "name": "sort", "in": "query", "schema": { "type": "string", "enum": ["created_at", "-created_at", "price", "-price", "name", "-name"], "default": "-created_at" } }
],
"responses": {
"200": {
"description": "One page",
"headers": { "Link": { "description": "rel=\"next\" URL when has_more is true", "schema": { "type": "string" } } },
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductList" } } }
},
"400": { "$ref": "#/components/responses/Problem" }
}
},
"post": {
"operationId": "createProduct",
"summary": "Create a product",
"parameters": [{ "$ref": "#/components/parameters/IdempotencyKey" }],
"requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductWrite" } } } },
"responses": {
"201": {
"description": "Created",
"headers": { "Location": { "schema": { "type": "string" } }, "ETag": { "schema": { "type": "string" } } },
"content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } }
},
"400": { "$ref": "#/components/responses/Problem" },
"409": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" }
}
}
},
"/v1/products/{id}": {
"parameters": [{ "name": "id", "in": "path", "required": true, "schema": { "type": "string" } }],
"get": {
"operationId": "getProduct",
"responses": {
"200": { "description": "The product", "headers": { "ETag": { "schema": { "type": "string" } } }, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"304": { "description": "Not modified (If-None-Match)" },
"404": { "$ref": "#/components/responses/Problem" }
}
},
"put": {
"operationId": "replaceProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"requestBody": { "required": true, "content": { "application/json": { "schema": { "$ref": "#/components/schemas/ProductWrite" } } } },
"responses": {
"200": { "description": "Replaced", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"412": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
},
"patch": {
"operationId": "patchProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"requestBody": { "required": true, "content": { "application/merge-patch+json": { "schema": { "type": "object" } } } },
"responses": {
"200": { "description": "Patched", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Product" } } } },
"412": { "$ref": "#/components/responses/Problem" },
"415": { "$ref": "#/components/responses/Problem" },
"422": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
},
"delete": {
"operationId": "deleteProduct",
"parameters": [{ "$ref": "#/components/parameters/IfMatch" }],
"responses": {
"204": { "description": "Deleted" },
"404": { "$ref": "#/components/responses/Problem" },
"412": { "$ref": "#/components/responses/Problem" },
"428": { "$ref": "#/components/responses/Problem" }
}
}
}
},
"components": {
"parameters": {
"IfMatch": { "name": "If-Match", "in": "header", "required": true, "schema": { "type": "string" }, "example": "\"v3\"" },
"IdempotencyKey": { "name": "Idempotency-Key", "in": "header", "schema": { "type": "string", "maxLength": 255 } }
},
"responses": {
"Problem": { "description": "RFC 9457 problem", "content": { "application/problem+json": { "schema": { "$ref": "#/components/schemas/Problem" } } } }
},
"schemas": {
"Status": { "type": "string", "enum": ["draft", "active", "archived"] },
"ProductWrite": {
"type": "object",
"additionalProperties": false,
"required": ["sku", "name", "price_cents", "currency", "status"],
"properties": {
"sku": { "type": "string", "minLength": 3, "maxLength": 32 },
"name": { "type": "string", "minLength": 1, "maxLength": 200 },
"price_cents": { "type": "integer", "minimum": 0, "maximum": 100000000 },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
"status": { "$ref": "#/components/schemas/Status" },
"tags": { "type": "array", "maxItems": 10, "items": { "type": "string", "minLength": 1, "maxLength": 30 } }
}
},
"Product": {
"description": "Response representation. Not an allOf over ProductWrite: allOf branches are validated independently, so ProductWrite's additionalProperties false would reject id and version.",
"type": "object",
"additionalProperties": false,
"required": ["id", "sku", "name", "price_cents", "currency", "status", "tags", "version", "created_at", "updated_at"],
"properties": {
"id": { "type": "string", "readOnly": true },
"sku": { "type": "string", "minLength": 3, "maxLength": 32 },
"name": { "type": "string", "minLength": 1, "maxLength": 200 },
"price_cents": { "type": "integer", "minimum": 0, "maximum": 100000000 },
"currency": { "type": "string", "pattern": "^[A-Z]{3}$" },
"status": { "$ref": "#/components/schemas/Status" },
"tags": { "type": "array", "items": { "type": "string" } },
"version": { "type": "integer", "readOnly": true },
"created_at": { "type": "string", "format": "date-time", "readOnly": true },
"updated_at": { "type": "string", "format": "date-time", "readOnly": true }
}
},
"ProductList": {
"type": "object",
"required": ["data", "has_more"],
"properties": {
"data": { "type": "array", "items": { "$ref": "#/components/schemas/Product" } },
"next_cursor": { "type": "string" },
"has_more": { "type": "boolean" }
}
},
"Problem": {
"type": "object",
"properties": {
"type": { "type": "string", "format": "uri-reference", "default": "about:blank" },
"title": { "type": "string" },
"status": { "type": "integer" },
"detail": { "type": "string" },
"instance": { "type": "string" },
"request_id": { "type": "string" },
"errors": {
"type": "array",
"items": { "type": "object", "properties": { "pointer": { "type": "string" }, "detail": { "type": "string" } } }
}
}
}
}
}
}// Package openapi embeds the hand-written OpenAPI 3.1 document and serves it
// together with an interactive reference page.
package openapi
import (
_ "embed"
"html/template"
"net/http"
)
//go:embed openapi.json
var spec []byte
// Spec returns the embedded document (for the contract test).
func Spec() []byte { return spec }
// SpecHandler serves GET /openapi.json.
func SpecHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "public, max-age=300")
_, _ = w.Write(spec)
})
}
// docsPage loads Scalar's API reference from its CDN, as in Scalar's README.
// Pin the package version in production; Swagger UI (swagger-ui-dist) can be
// served the same way.
var docsPage = template.Must(template.New("docs").Parse(`<!doctype html>
<html>
<head>
<title>Products API reference</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
</head>
<body>
<div id="app"></div>
<script type="module">
import { createApiReference } from 'https://cdn.jsdelivr.net/npm/@scalar/api-reference/esm.js'
createApiReference('#app', { url: {{.}} })
</script>
</body>
</html>
`))
// DocsHandler serves GET /docs pointing at specURL.
func DocsHandler(specURL string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
_ = docsPage.Execute(w, specURL)
})
}swaggo/swag vs oapi-codegen vs ogen, and generated clients Important
In plain words: There are two directions. Code-first: write Go, annotate it with comments, generate the spec (swaggo/swag; huma builds the spec from Go types at runtime). Spec-first: write the spec, generate Go server interfaces, models and clients from it (oapi-codegen, ogen). Generated clients are the payoff of either: callers get typed methods instead of hand-written HTTP.
Common misunderstanding: "swag produces OpenAPI 3." The stable line does not: the README says "Swag converts Go annotations to Swagger Documentation 2.0"; OpenAPI 3.1 output exists only behind a --v3.1 flag on the v2 branch, whose latest tag is v2.0.0-rc6 (module proxy, September 2026). And "spec-first is slower": with oapi-codegen's strict server you implement one typed method per operation and never touch JSON or headers.
Definition: swag init parses comments such as // @Summary, // @Param id path int true "Account ID", // @Success, // @Router and writes a docs folder with docs/docs.go that your main imports; http-swagger (net/http, gorilla/mux, chi) or framework plugins (gin, echo, fiber, ...) serve Swagger UI for the generated doc.json. oapi-codegen (v2.9.0 is current; module github.com/oapi-codegen/oapi-codegen/v2 since v2.3.0) generates from OpenAPI 3.0 and 3.1, for std-http-server (net/http), chi-server, echo-server, gin-server, fiber-server, gorilla-server and iris-server, plus a strict-server and a client; its README says it "requires Go 1.26+ to build and install. The generated code requires Go 1.26+ as well". ogen (v1.25.0, its go.mod says go 1.26.0) is an "OpenAPI v3 Code Generator for Go" with "No reflection or interface{}", generated JSON encoding via go-faster/jx, "Validation is code-generated according to spec", a static radix router, Optional[T]/Nullable[T] wrappers, OpenTelemetry support, and can serve the spec and Swagger UI with WithDocs.
spec-first (oapi-codegen, expected, not run: needs Go 1.26 for the generated code)
1 oapi-codegen.yaml package: api · generate: {std-http-server: true, strict-server: true, models: true, client: true}
2 go tool oapi-codegen -config oapi-codegen.yaml openapi.json > api/api.gen.go
3 type StrictServerInterface interface { ListProducts(ctx, ListProductsRequestObject) (ListProductsResponseObject, error); ... }
4 you write: type Server struct{ svc *service.Service } + one method per operation
5 mux := http.NewServeMux(); api.HandlerFromMux(api.NewStrictHandler(srv, nil), mux)
6 clients: api.NewClientWithResponses("https://api.example.test") -> typed ListProductsWithResponseReal scenario: a team with a Gin monolith adding swag annotations to publish docs quickly; a platform team that designs APIs in review as OpenAPI files and generates Go servers and TypeScript clients from them; a latency-sensitive service choosing ogen for generated JSON code; an SDK team publishing clients in five languages from one document.
| swaggo/swag | oapi-codegen | ogen | Hand-written spec + drift test (this chapter) | |
|---|---|---|---|---|
| Direction | Code-first (comments) | Spec-first | Spec-first | Spec-first, code by hand |
| Spec version | Swagger 2.0 (v1.16.6); 3.1 via --v3.1 in v2 RC | Reads 3.0 and 3.1 (3.2 operations too) | OpenAPI v3 | 3.1.0 |
| Generates | Spec, docs.go | Server interface, strict server, models, client | Server, client, validation, JSON codec, router | Nothing |
| Routers | gin, echo, fiber, net/http, chi, gorilla/mux, ... (UI plugins) | std net/http, Chi, Echo, Fiber, Gin, gorilla, Iris | Its own router (an http.Handler) | Your ServeMux |
| Runtime dependency | Swagger UI handler | github.com/oapi-codegen/runtime | ogen runtime, go-faster/jx | None |
| Minimum Go | go 1.18 in its module | 1.26+ for generated code | go 1.26.0 in its module | Your choice (1.24 here) |
| Drift risk | Comments vs code | None for generated parts | None for generated parts | Caught by the test |
| Best when | Existing code, quick docs | Contract reviewed first, many clients | Performance, strict typing | Small APIs, teaching, no generator |
Fix / how to use it: pin generators with Go 1.24's tool directive (go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v2.9.0, then go tool oapi-codegen ...), commit the generated files, and fail CI when regeneration changes them. The hand-written client below is what a generator writes for you; its All method follows next_cursor with a Go 1.23 range-over-func iterator.
// Package client is a small typed client of the API: the kind of code an
// OpenAPI generator (oapi-codegen, ogen) writes for you from openapi.json.
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"iter"
"net/http"
"net/url"
"academy/rest-api-project/dto"
"academy/rest-api-project/problem"
)
// Client talks to one base URL.
type Client struct {
BaseURL string
HTTP *http.Client
}
// Error is a non-2xx answer, decoded from application/problem+json.
type Error struct{ Problem problem.Problem }
func (e *Error) Error() string {
return fmt.Sprintf("%d %s: %s", e.Problem.Status, e.Problem.Title, e.Problem.Detail)
}
// Create posts a product with an Idempotency-Key so it is safe to retry.
func (c *Client) Create(ctx context.Context, key string, in dto.ProductWrite) (dto.ProductView, error) {
body, _ := json.Marshal(in)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.BaseURL+"/v1/products", bytes.NewReader(body))
if err != nil {
return dto.ProductView{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Idempotency-Key", `"`+key+`"`)
var out dto.ProductView
return out, c.do(req, http.StatusCreated, &out)
}
// All iterates every product matching query, following next_cursor page by
// page (range-over-func, Go 1.23). Stop early by breaking out of the loop.
func (c *Client) All(ctx context.Context, query url.Values) iter.Seq2[dto.ProductView, error] {
return func(yield func(dto.ProductView, error) bool) {
q := url.Values{}
for k, v := range query {
q[k] = v
}
for {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.BaseURL+"/v1/products?"+q.Encode(), nil)
if err != nil {
yield(dto.ProductView{}, err)
return
}
var page dto.ListView
if err := c.do(req, http.StatusOK, &page); err != nil {
yield(dto.ProductView{}, err)
return
}
for _, p := range page.Data {
if !yield(p, nil) {
return
}
}
if !page.HasMore {
return
}
q.Set("cursor", page.NextCursor)
}
}
}
func (c *Client) do(req *http.Request, want int, out any) error {
hc := c.HTTP
if hc == nil {
hc = http.DefaultClient
}
resp, err := hc.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != want {
var e Error
_ = json.NewDecoder(resp.Body).Decode(&e.Problem)
e.Problem.Status = resp.StatusCode
return &e
}
return json.NewDecoder(resp.Body).Decode(out)
}API documentation serving: Swagger UI / Scalar Good to know
In plain words: The service serves its own contract at /openapi.json and an interactive reference page at /docs that loads that contract in the browser. Here the page uses Scalar; Swagger UI works the same way.
Common misunderstanding: "The docs page needs a separate deployment." A static HTML page that loads a JavaScript bundle and points it at /openapi.json is enough; serving it from the API means the docs always describe the running version. The real decisions are security ones: should /docs be public, and may the page load scripts from a CDN.
Definition: Scalar's README: "All you need is a single HTML file", importing createApiReference from https://cdn.jsdelivr.net/npm/@scalar/api-reference/esm.js and calling it with the document URL. Swagger UI is published as swagger-ui-dist, "a dependency-free module that includes everything you need to serve Swagger UI in a server-side project", or as a /dist folder you copy to your server. ogen can embed both the document and Swagger UI (/docs/, /docs/openapi.json, /docs/openapi.yaml); swag's http-swagger serves Swagger UI for its generated doc.json.
1 browser GET /docs -> HTML (html/template escapes the spec URL into the script)
2 script import from CDN -> createApiReference('#app', { url: "/openapi.json" })
3 browser GET /openapi.json -> embedded spec, Cache-Control: public, max-age=300
4 "Try it" uses servers[0].url = "/": real requests to the same origin (no CORS needed)Real scenario: an internal platform where every service exposes /docs behind SSO; a public API whose docs site is built from the same document in CI; a locked-down environment where the CDN is blocked and the bundle must be vendored and embedded with //go:embed.
| Option | Hosting | Notes |
|---|---|---|
| Scalar (CDN script) | One HTML page, this chapter | Pin the package version in production |
Swagger UI (swagger-ui-dist) | Copy /dist, serve with http.FileServerFS | The classic; "Try it out" console |
ogen WithDocs | Generated handler | Spec + Swagger UI from the generated package |
swag + http-swagger | Generated docs package | Swagger 2.0 document |
Fix / how to use it: see openapi.go above; add a Content-Security-Policy that allows only the CDN you chose, or embed the bundle.
httptest end-to-end tests and the in-memory repository for tests Must-know
In plain words: Most tests of an API should send real HTTP requests through the real handler stack (routing, middleware, decoding, error mapping, service) to a repository that lives in memory. httptest.NewServer gives you a real listener in the test process; the in-memory repository gives you a fresh, fast, isolated store per test.
Common misunderstanding: "Unit-test every handler with mocks of the service." Those tests repeat the implementation and miss the bugs that matter: a route registered with the wrong method, middleware in the wrong order, a missing Content-Type, a status that differs from the spec. Mat Ryer: "I err on the side of end-to-end testing at this level, rather than unit testing all the pieces inside", and "If I diligently test every layer, I can end up saying the same things multiple times in slightly different ways." Unit tests still pay for pure logic (merge patch, cursor codec, validation, the service rules).
Definition: three levels are used here. httptest.NewRecorder + handler.ServeHTTP for one component (problem, openapi); httptest.NewServer(httpapi.NewServer(deps)) with memrepo for the HTTP contract (httpapi_test.go: CRUD lifecycle, every error status, pagination by following Link, 405 as a problem, idempotent create, the rate limit hook, the spec drift test); and app.Run in a goroutine for the whole program (app_test.go: real config, real listener, readiness wait, typed client, graceful shutdown). t.Context() (Go 1.24) bounds every request; slog.DiscardHandler (Go 1.24) silences logs. A real-database test of pgrepo would add a PostgreSQL container and the same tests behind a build tag.
1 newAPI(t): svc := service.New(memrepo.New(), fakeClock, seqIDs)
2 srv := httptest.NewServer(httpapi.NewServer(Deps{...})) real TCP on 127.0.0.1
3 test: POST -> 201 · GET If-None-Match -> 304 · PATCH If-Match -> 200 v2
PATCH stale -> 412 · PUT no If-Match -> 428 · DELETE -> 204 · GET -> 404 problem
4 t.Cleanup(srv.Close); each test gets its own repository: no shared state, t.Parallel() safeReal scenario: a refactor of the middleware order caught by a 405 test; a new endpoint that fails the contract test until it is documented; a regression where a validation error became a 500, caught by the table of error cases; CI running the whole API suite in about a second without Docker.
| Level | Tool | Catches | Speed |
|---|---|---|---|
| Pure logic | Table tests | Merge patch, cursors, validation, rules | Microseconds |
| Component | httptest.NewRecorder | One handler's output | Microseconds |
| HTTP contract | httptest.NewServer + memrepo | Routing, middleware, status codes, headers, spec drift | Milliseconds |
| Program | app.Run + readiness wait | Wiring, config, shutdown | Tens of ms |
| Storage | Real PostgreSQL (container) | SQL, indexes, constraints | Seconds |
Fix / how to use it: the suite below is the specification of the API in executable form. More on httptest, table tests and coverage in Testing & Benchmarking.
package httpapi_test
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"academy/rest-api-project/dto"
"academy/rest-api-project/httpapi"
"academy/rest-api-project/idempotency"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/openapi"
"academy/rest-api-project/pagination"
"academy/rest-api-project/problem"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// newAPI starts the real handler stack over the in-memory repository: an
// end-to-end test of routing, middleware, decoding, service and storage.
func newAPI(t *testing.T, limiter httpapi.Limiter) *httptest.Server {
t.Helper()
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
n := 0
svc := service.New(memrepo.New(),
func() time.Time { at = at.Add(time.Second); return at },
func() string { n++; return fmt.Sprintf("prd_%03d", n) })
srv := httptest.NewServer(httpapi.NewServer(httpapi.Deps{
Logger: slog.New(slog.DiscardHandler),
Products: svc,
Cursors: pagination.Codec{Key: []byte("0123456789abcdef")},
Idempotency: idempotency.NewStore(24*time.Hour, time.Now),
Limiter: limiter,
MaxBodyBytes: 4 << 10,
}))
t.Cleanup(srv.Close)
return srv
}
func do(t *testing.T, method, url, ctype, body string, hdr ...string) *http.Response {
t.Helper()
req, err := http.NewRequestWithContext(t.Context(), method, url, strings.NewReader(body))
if err != nil {
t.Fatal(err)
}
if ctype != "" {
req.Header.Set("Content-Type", ctype)
}
for i := 0; i+1 < len(hdr); i += 2 {
req.Header.Set(hdr[i], hdr[i+1])
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { resp.Body.Close() })
return resp
}
func decodeAs[T any](t *testing.T, r *http.Response) T {
t.Helper()
var v T
if err := json.NewDecoder(r.Body).Decode(&v); err != nil {
t.Fatal(err)
}
return v
}
const mug = `{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}`
func TestCRUDLifecycle(t *testing.T) {
api := newAPI(t, nil)
created := do(t, "POST", api.URL+"/v1/products", "application/json", mug)
if created.StatusCode != 201 || created.Header.Get("ETag") != `"v1"` {
t.Fatalf("create: %d etag %q", created.StatusCode, created.Header.Get("ETag"))
}
loc := api.URL + created.Header.Get("Location")
if r := do(t, "GET", loc, "", "", "If-None-Match", `"v1"`); r.StatusCode != 304 {
t.Fatalf("conditional GET: %d", r.StatusCode)
}
// Merge patch: change the price, activate, delete the tags member.
patched := do(t, "PATCH", loc, "application/merge-patch+json",
`{"price_cents":1200,"status":"active","tags":null}`, "If-Match", `"v1"`)
view := decodeAs[dto.ProductView](t, patched)
if patched.StatusCode != 200 || view.PriceCents != 1200 || view.Version != 2 || len(view.Tags) != 0 {
t.Fatalf("patch: %d %+v", patched.StatusCode, view)
}
if r := do(t, "PATCH", loc, "application/merge-patch+json", `{"name":"Cup"}`, "If-Match", `"v1"`); r.StatusCode != 412 {
t.Fatalf("stale If-Match: %d, want 412", r.StatusCode)
}
if r := do(t, "PUT", loc, "application/json", mug); r.StatusCode != 428 {
t.Fatalf("PUT without If-Match: %d, want 428", r.StatusCode)
}
if r := do(t, "PATCH", loc, "application/merge-patch+json", `{"id":"prd_999"}`, "If-Match", `"v2"`); r.StatusCode != 400 {
t.Fatalf("patching a read-only member: %d, want 400", r.StatusCode)
}
if r := do(t, "DELETE", loc, "", "", "If-Match", `"v2"`); r.StatusCode != 204 {
t.Fatalf("delete: %d", r.StatusCode)
}
gone := do(t, "GET", loc, "", "")
p := decodeAs[problem.Problem](t, gone)
if gone.StatusCode != 404 || p.Type != "about:blank" || p.Title != "Not Found" || p.RequestID == "" {
t.Fatalf("after delete: %d %+v", gone.StatusCode, p)
}
}
func TestRequestErrorsAreProblems(t *testing.T) {
api := newAPI(t, nil)
url := api.URL + "/v1/products"
cases := []struct {
name, ctype, body string
status int
}{
{"validation", "application/json", `{"sku":"AB","name":"","price_cents":-1,"currency":"eur","status":"sold"}`, 422},
{"unknown field", "application/json", `{"sku":"MUG-2","colour":"red"}`, 400},
{"wrong type", "application/json", `{"sku":"MUG-2","price_cents":"9"}`, 400},
{"two objects", "application/json", mug + mug, 400},
{"media type", "text/plain", mug, 415},
{"too large", "application/json", `{"name":"` + strings.Repeat("x", 5000) + `"}`, 413},
}
// The same oversized body with an Idempotency-Key is cut by the idempotency
// middleware, which reads the body first.
if r := do(t, "POST", url, "application/json", `{"name":"`+strings.Repeat("x", 5000)+`"}`, "Idempotency-Key", `"big"`); r.StatusCode != 413 {
t.Fatalf("oversized body with a key: %d, want 413", r.StatusCode)
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := do(t, "POST", url, c.ctype, c.body)
if r.StatusCode != c.status || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("status %d (%s), want %d", r.StatusCode, r.Header.Get("Content-Type"), c.status)
}
p := decodeAs[problem.Problem](t, r)
if p.Status != c.status {
t.Fatalf("body status %d", p.Status)
}
if c.status == 422 {
var ptrs []string
for _, e := range p.Errors {
ptrs = append(ptrs, e.Pointer)
}
if !slices.Equal(ptrs, []string{"/sku", "/name", "/price_cents", "/currency", "/status"}) {
t.Fatalf("pointers %v", ptrs)
}
}
})
}
}
func TestPaginationFollowsLinkHeader(t *testing.T) {
api := newAPI(t, nil)
for i := range 7 {
body := fmt.Sprintf(`{"sku":"SKU-%d","name":"P%d","price_cents":%d,"currency":"EUR","status":"active"}`, i, i, 100*(i%3))
if r := do(t, "POST", api.URL+"/v1/products", "application/json", body); r.StatusCode != 201 {
t.Fatalf("seed %d: %d", i, r.StatusCode)
}
}
next := "/v1/products?sort=price&limit=3"
var ids []string
var firstCursor string
for next != "" {
r := do(t, "GET", api.URL+next, "", "")
page := decodeAs[dto.ListView](t, r)
for _, p := range page.Data {
ids = append(ids, p.ID)
}
if firstCursor == "" {
firstCursor = page.NextCursor
}
next = ""
if link := r.Header.Get("Link"); link != "" {
next = strings.TrimPrefix(strings.SplitN(link, ">", 2)[0], "<")
}
}
sorted := slices.Clone(ids)
slices.Sort(sorted)
if len(ids) != 7 || len(slices.Compact(sorted)) != 7 {
t.Fatalf("walked %v", ids)
}
// A cursor minted for sort=price is rejected for sort=name.
if r := do(t, "GET", api.URL+"/v1/products?sort=name&cursor="+firstCursor, "", ""); r.StatusCode != 400 {
t.Fatalf("cursor reuse with another sort: %d", r.StatusCode)
}
}
func TestMuxErrorsBecomeProblems(t *testing.T) {
api := newAPI(t, nil)
r := do(t, "DELETE", api.URL+"/v1/products", "", "")
if r.StatusCode != 405 || !strings.Contains(r.Header.Get("Allow"), "POST") || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("405: %d allow=%q ct=%q", r.StatusCode, r.Header.Get("Allow"), r.Header.Get("Content-Type"))
}
if r := do(t, "GET", api.URL+"/v2/products", "", ""); r.StatusCode != 404 || r.Header.Get("Content-Type") != problem.MediaType {
t.Fatalf("unknown version: %d", r.StatusCode)
}
}
func TestIdempotentCreate(t *testing.T) {
api := newAPI(t, nil)
key := "Idempotency-Key"
a := decodeAs[dto.ProductView](t, do(t, "POST", api.URL+"/v1/products", "application/json", mug, key, `"k-1"`))
retry := do(t, "POST", api.URL+"/v1/products", "application/json", mug, key, `"k-1"`)
b := decodeAs[dto.ProductView](t, retry)
if a.ID != b.ID || retry.StatusCode != 201 || retry.Header.Get(idempotency.ReplayedHeader) != "true" {
t.Fatalf("retry created a second product or was not replayed: %s vs %s", a.ID, b.ID)
}
// Without the key the same body hits the unique SKU: 409.
if r := do(t, "POST", api.URL+"/v1/products", "application/json", mug); r.StatusCode != 409 {
t.Fatalf("duplicate without key: %d", r.StatusCode)
}
}
type denyAll struct{}
func (denyAll) Allow(*http.Request) (bool, time.Duration) { return false, 1500 * time.Millisecond }
func TestRateLimitHook(t *testing.T) {
api := newAPI(t, denyAll{})
r := do(t, "GET", api.URL+"/v1/products", "", "", "X-Request-ID", "gw-123")
p := decodeAs[problem.Problem](t, r)
if r.StatusCode != 429 || r.Header.Get("Retry-After") != "2" || p.RequestID != "gw-123" {
t.Fatalf("429: %d retry-after %q %+v", r.StatusCode, r.Header.Get("Retry-After"), p)
}
}
// TestContractMatchesRoutes fails when a route is added without being
// documented, or documented without being routed.
func TestContractMatchesRoutes(t *testing.T) {
var doc struct {
Paths map[string]map[string]json.RawMessage `json:"paths"`
}
if err := json.Unmarshal(openapi.Spec(), &doc); err != nil {
t.Fatal(err)
}
var inSpec []string
for path, item := range doc.Paths {
for method := range item {
if method != "parameters" {
inSpec = append(inSpec, strings.ToUpper(method)+" "+path)
}
}
}
routed := httpapi.Routes()
slices.Sort(inSpec)
slices.Sort(routed)
if !slices.Equal(inSpec, routed) {
t.Fatalf("spec and routes differ:\nspec %v\nrouted %v", inSpec, routed)
}
}
func TestDocsAndSpecAreServed(t *testing.T) {
api := newAPI(t, nil)
if r := do(t, "GET", api.URL+"/openapi.json", "", ""); r.StatusCode != 200 {
t.Fatalf("spec: %d", r.StatusCode)
}
r := do(t, "GET", api.URL+"/docs", "", "")
b, _ := io.ReadAll(r.Body)
if r.StatusCode != 200 || !strings.Contains(string(b), "createApiReference") {
t.Fatalf("docs: %d", r.StatusCode)
}
}
// failingRepo makes every write fail with an internal error.
type failingRepo struct{ service.Repository }
func (failingRepo) Insert(context.Context, product.Product) error { return errors.New("disk on fire") }
// TestServerErrorCauseIsLoggedNotSent: the client gets a bare 500 problem,
// the access log gets the cause, also behind the idempotency middleware.
func TestServerErrorCauseIsLoggedNotSent(t *testing.T) {
var logs bytes.Buffer
svc := service.New(failingRepo{}, time.Now, func() string { return "prd_x" })
srv := httptest.NewServer(httpapi.NewServer(httpapi.Deps{
Logger: slog.New(slog.NewJSONHandler(&logs, nil)),
Products: svc,
Cursors: pagination.Codec{Key: []byte("0123456789abcdef")},
Idempotency: idempotency.NewStore(time.Hour, time.Now),
MaxBodyBytes: 4 << 10,
}))
defer srv.Close()
r := do(t, "POST", srv.URL+"/v1/products", "application/json", mug, "Idempotency-Key", `"k-500"`)
body, _ := io.ReadAll(r.Body)
if r.StatusCode != 500 || strings.Contains(string(body), "disk on fire") {
t.Fatalf("status %d, body leaks the cause: %s", r.StatusCode, body)
}
srv.Close() // flush: the access log line is written after the handler returns
if !strings.Contains(logs.String(), `"err":"create MUG-1: disk on fire"`) {
t.Fatalf("cause not logged:\n%s", logs.String())
}
}package memrepo_test
import (
"fmt"
"testing"
"time"
"academy/rest-api-project/memrepo"
"academy/rest-api-project/product"
"academy/rest-api-project/service"
)
// The in-memory repository must satisfy the same port as the SQL one.
var _ service.Repository = (*memrepo.Repo)(nil)
func TestKeysetWalkVisitsEveryRowOnce(t *testing.T) {
r := memrepo.New()
at := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
for i := range 25 {
// Five products share each price, so ties must be broken by id.
p := product.Product{ID: fmt.Sprintf("prd_%02d", i), SKU: fmt.Sprintf("SKU-%02d", i), PriceCents: int64(100 * (i % 5)), Status: product.StatusActive, CreatedAt: at}
if err := r.Insert(t.Context(), p); err != nil {
t.Fatal(err)
}
}
seen := map[string]bool{}
q := product.ListQuery{Sort: product.SortPrice, Desc: true, Limit: 7}
for pages := 0; ; pages++ {
rows, err := r.List(t.Context(), q)
if err != nil {
t.Fatal(err)
}
more := len(rows) > q.Limit
if more {
rows = rows[:q.Limit]
}
for _, p := range rows {
if seen[p.ID] {
t.Fatalf("row %s returned twice", p.ID)
}
seen[p.ID] = true
}
if !more {
break
}
c := product.CursorAfter(rows[len(rows)-1])
q.After = &c
}
if len(seen) != 25 {
t.Fatalf("visited %d rows, want 25", len(seen))
}
}
func TestUpdateChecksVersion(t *testing.T) {
r := memrepo.New()
p := product.Product{ID: "prd_1", SKU: "A", Version: 1}
_ = r.Insert(t.Context(), p)
p.Version = 2
if err := r.Update(t.Context(), p, 1); err != nil {
t.Fatal(err)
}
if err := r.Update(t.Context(), p, 1); err != product.ErrVersionMismatch {
t.Fatalf("stale write: got %v", err)
}
}Graceful shutdown and health endpoints Must-know
In plain words: On SIGTERM the service first says "not ready" so the load balancer stops sending new requests, waits a moment for that to take effect, then stops accepting connections and lets the requests already running finish, with an upper time limit. /healthz says "the process is alive"; /readyz says "send me traffic".
Common misunderstanding: "srv.Shutdown is enough." Shutdown "works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle". It waits forever unless its context has a deadline, and closing the listener at once can still race with a load balancer that has not yet noticed the instance is going away, which is why the readiness flip and a drain delay come first. Also, Serve returns ErrServerClosed immediately: "Make sure the program doesn't exit and waits instead for Shutdown to return".
Definition: liveness (/healthz) must not depend on downstream systems, or one database outage restarts every pod; readiness (/readyz) checks what this instance needs to serve (the repository's Ping) and fails while draining. Kubernetes: "Readiness probes run on the container during its whole lifecycle", and a pod whose containers report not ready "does not receive traffic through Kubernetes" Services; its own API server exposes livez and readyz and notes that "The healthz endpoint is deprecated (since Kubernetes v1.16)". The shutdown sequence in Run: context canceled by signal.NotifyContext → draining = true (readyz 503) → sleep API_DRAIN_DELAY → srv.Shutdown(ctx with API_SHUTDOWN_TIMEOUT) → wait for Serve to return ErrServerClosed → return nil.
t=0.000 SIGTERM ctx canceled · log "shutting down" drain_delay=1s timeout=10s
t=0.000 draining=true GET /readyz -> 503 {"detail":"shutting down"} (real run, see Lab)
t=0-1s load balancer marks the instance unready, stops new traffic
t=1.000 srv.Shutdown(ctx) listener closed, idle conns closed, waits for active requests
t=1.001 Serve returns ErrServerClosed -> Run returns nil -> exit 0 · log "stopped"
if requests still run at t=11s: Shutdown returns context deadline exceeded -> exit 1Real scenario: a rolling deploy that used to produce a burst of 502s; a long export request cut off at pod termination; a liveness probe that checked the database and caused a restart storm during a database failover; a test that waits for /readyz instead of sleeping.
| Endpoint / knob | Answers | Checks | Kubernetes field |
|---|---|---|---|
/healthz (liveness) | 200 while the process serves HTTP | Nothing external | livenessProbe |
/readyz (readiness) | 200 or 503 problem | Repository Ping, draining flag | readinessProbe |
| Startup | (optional) | Migrations done, caches warm | startupProbe |
API_DRAIN_DELAY | Time for endpoints to update | Shorter than terminationGracePeriodSeconds | |
API_SHUTDOWN_TIMEOUT | Bound for in-flight requests | Same budget |
Fix / how to use it: Run in After implements the sequence; signals, NotifyContext and process lifecycle in general are in OS Processes, Signals & Graceful Shutdown.
Structured logging, request IDs and the rate limiting hook Important
In plain words: Every request gets an ID (taken from a trusted X-Request-ID or generated), which is echoed in the response header, written into every problem body and into one structured JSON log line per request. A rate limiting hook sits in the middleware chain: by default it does nothing; plug in a limiter and it answers 429 with Retry-After.
Common misunderstanding: "Log the error message in the response so the client can report it." Send the request ID instead; the log has the cause. And "rate limiting is a feature of the API code". The policy (per key, per IP, global, token bucket or sliding window) usually changes independently of the endpoints, and often lives in a gateway; the API only needs a hook and a consistent 429.
Definition: requestID middleware validates incoming IDs against ^[A-Za-z0-9._-]{1,64}$ (so a client cannot inject log lines), stores the ID under an unexported context key, and sets the response header; problem.Write copies it into request_id. logRequests wraps the writer to capture the status, uses r.Pattern (Go 1.23: "the ServeMux pattern (if any) that matched the request") as a low-cardinality route label, and logs at ERROR with the internal cause when writeError attached one through the recorder's SetError. recoverPanics turns a panic into a 500 problem and re-panics http.ErrAbortHandler. The Limiter interface is one method, Allow(r) (ok bool, retryAfter time.Duration); RFC 6585 says 429 "indicates that the user has sent too many requests in a given amount of time", and the IETF RateLimit draft "defines the RateLimit-Policy and RateLimit HTTP header fields" for advertising quotas.
1 in X-Request-ID: gw-123 (valid) -> ctx + response header
2 out 429 Retry-After: 2 {"type":".../rate-limited","status":429,"request_id":"gw-123"}
3 log {"level":"INFO","msg":"request","method":"GET","path":"/v1/products",
"pattern":"GET /v1/products","status":200,"duration":41625,"request_id":"e924..."}
4 500 {"level":"ERROR",...,"err":"<internal cause>"} client sees only about:blank 500 + request_idReal scenario: a customer pastes a request ID into a ticket and support finds the log line in seconds; a dashboard of p99 latency per pattern rather than per raw path (no cardinality explosion from IDs); a partner hammering the list endpoint gets 429s with a clear retry time; a gateway that already assigns IDs, which the service keeps.
| Concern | This chapter | Where it is taught |
|---|---|---|
| Middleware order | requestID → recover → log → rateLimit → mux | Middlewares |
| Token bucket / sliding window | Limiter interface only | Rate Limiting in Go |
slog handlers, levels | JSON handler from Run | CLI Flags, Env & Logging |
| Request ID in ctx | Unexported key, accessor | context |
| Traces | (not included) | OpenTelemetry instrumentation wrapped around the handler |
Fix / how to use it:
package httpapi
import (
"context"
"crypto/rand"
"encoding/hex"
"log/slog"
"math"
"net/http"
"regexp"
"strconv"
"time"
"academy/rest-api-project/problem"
)
type requestIDKey struct{}
// RequestID returns the id the requestID middleware put in ctx.
func RequestID(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
}
var validRequestID = regexp.MustCompile(`^[A-Za-z0-9._-]{1,64}$`)
// requestID accepts a sane X-Request-ID from the caller (a gateway) or makes
// one, stores it in ctx and echoes it; problem.Write copies it into bodies.
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-ID")
if !validRequestID.MatchString(id) {
b := make([]byte, 8)
_, _ = rand.Read(b)
id = hex.EncodeToString(b)
}
w.Header().Set("X-Request-ID", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), requestIDKey{}, id)))
})
}
// statusRecorder remembers what the handler did, for the access log.
type statusRecorder struct {
http.ResponseWriter
status int
err error
}
func (s *statusRecorder) WriteHeader(code int) {
if s.status == 0 {
s.status = code
}
s.ResponseWriter.WriteHeader(code)
}
func (s *statusRecorder) Write(b []byte) (int, error) {
if s.status == 0 {
s.status = http.StatusOK
}
return s.ResponseWriter.Write(b)
}
// SetError lets writeError attach the internal cause of a 5xx.
func (s *statusRecorder) SetError(err error) { s.err = err }
// Unwrap keeps http.ResponseController working through the wrapper.
func (s *statusRecorder) Unwrap() http.ResponseWriter { return s.ResponseWriter }
// logRequests writes one structured line per request.
func logRequests(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w}
next.ServeHTTP(rec, r)
level := slog.LevelInfo
attrs := []slog.Attr{
slog.String("method", r.Method), slog.String("path", r.URL.Path),
slog.String("pattern", r.Pattern), slog.Int("status", rec.status),
slog.Duration("duration", time.Since(start)), slog.String("request_id", RequestID(r.Context())),
}
if rec.err != nil {
level = slog.LevelError
attrs = append(attrs, slog.String("err", rec.err.Error()))
}
log.LogAttrs(r.Context(), level, "request", attrs...)
})
}
// recoverPanics turns a panic into a 500 problem instead of a dropped
// connection, and logs it with the request id.
func recoverPanics(log *slog.Logger, next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
if v == http.ErrAbortHandler {
panic(v)
}
log.ErrorContext(r.Context(), "panic", "value", v, "request_id", RequestID(r.Context()))
problem.Write(w, r, problem.New(http.StatusInternalServerError, "", "", ""))
}
}()
next.ServeHTTP(w, r)
})
}
// rateLimit is the hook: the policy lives behind Limiter.
func rateLimit(l Limiter, next http.Handler) http.Handler {
if l == nil {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if ok, after := l.Allow(r); !ok {
w.Header().Set("Retry-After", strconv.Itoa(int(math.Ceil(after.Seconds()))))
problem.Write(w, r, problem.New(http.StatusTooManyRequests, "rate-limited", "Too many requests", ""))
return
}
next.ServeHTTP(w, r)
})
}
// fallbackRecorder captures the mux's own 404/405 replies.
type fallbackRecorder struct {
header http.Header
status int
}
func (f *fallbackRecorder) Header() http.Header { return f.header }
func (f *fallbackRecorder) Write(b []byte) (int, error) { return len(b), nil }
func (f *fallbackRecorder) WriteHeader(code int) { f.status = code }
// problemFallback keeps ServeMux's routing (including 405 + Allow) but
// rewrites its plain-text 404 and 405 bodies as Problem Details.
func problemFallback(mux *http.ServeMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h, pattern := mux.Handler(r)
if pattern != "" {
mux.ServeHTTP(w, r)
return
}
rec := &fallbackRecorder{header: http.Header{}}
h.ServeHTTP(rec, r)
switch rec.status {
case http.StatusNotFound, http.StatusMethodNotAllowed:
if allow := rec.header.Get("Allow"); allow != "" {
w.Header().Set("Allow", allow)
}
problem.Write(w, r, problem.New(rec.status, "", "", ""))
default: // redirects (trailing slash, cleaned paths)
mux.ServeHTTP(w, r)
}
})
}Mechanics
Decoding a body safely Must-know
decode[T] in codec.go performs five checks in this order, and each has its own status:
| Step | Code | Failure | Status |
|---|---|---|---|
| 1 | mime.ParseMediaType(r.Header.Get("Content-Type")) | Missing or other media type (parameters such as charset are allowed) | 415 |
| 2 | http.MaxBytesReader(w, r.Body, max) | Read beyond the limit returns *http.MaxBytesError ("prevents clients from accidentally or maliciously sending a large request") | 413 |
| 3 | dec.DisallowUnknownFields() then Decode(&v) | Syntax error, unknown member ("object keys which do not match any non-ignored, exported fields"), *json.UnmarshalTypeError | 400 |
| 4 | dec.Decode(&struct{}{}) must return io.EOF | A second JSON value after the first (400); the size limit tripping while reading trailing data (413 via the same decodeProblem) | 400 / 413 |
| 5 | v.Valid(ctx) | Violations | 422 |
Only types are inspected (errors.As for *http.MaxBytesError and *json.UnmarshalTypeError); the decoder's message text goes into detail only, because Go 1.27 re-implemented encoding/json on encoding/json/v2 and says "the exact text of error messages may differ". JSON v2 also "rejects invalid UTF-8 in JSON strings and rejects duplicate names within a JSON object" when you use the v2 API directly, which matters when a proxy and your service might resolve a duplicated member such as two "price_cents" differently.
package httpapi
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strings"
"academy/rest-api-project/problem"
"academy/rest-api-project/validation"
)
// validator is what a request DTO implements to be checked after decoding.
type validator interface {
Valid(ctx context.Context) []validation.Violation
}
// decode reads exactly one JSON object of type T from a bounded body,
// rejects unknown fields, then validates it. Every failure is a ready-made
// Problem, so handlers stay linear.
func decode[T validator](w http.ResponseWriter, r *http.Request, maxBytes int64, mediaType string) (T, *problem.Problem) {
var v T
if p := requireMediaType(r, mediaType); p != nil {
return v, p
}
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxBytes))
dec.DisallowUnknownFields()
if err := dec.Decode(&v); err != nil {
return v, decodeProblem(err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
if tooBig := new(http.MaxBytesError); errors.As(err, &tooBig) {
return v, decodeProblem(err) // the limit can trip while reading trailing data
}
return v, problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "body must contain a single JSON object")
}
if errs := v.Valid(r.Context()); len(errs) > 0 {
return v, problem.Validation(errs)
}
return v, nil
}
func requireMediaType(r *http.Request, want string) *problem.Problem {
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mt != want {
return problem.New(http.StatusUnsupportedMediaType, "unsupported-media-type", "Unsupported media type",
fmt.Sprintf("Content-Type must be %s", want))
}
return nil
}
// decodeProblem maps decoder errors by type. Message texts of encoding/json
// are not a stable API (Go 1.27 says they may differ), so only the detail
// string carries them.
func decodeProblem(err error) *problem.Problem {
var tooBig *http.MaxBytesError
var typeErr *json.UnmarshalTypeError
switch {
case errors.As(err, &tooBig):
return problem.New(http.StatusRequestEntityTooLarge, "body-too-large", "Request body too large",
fmt.Sprintf("limit is %d bytes", tooBig.Limit))
case errors.As(err, &typeErr):
p := problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", "a field has the wrong JSON type")
p.Errors = []validation.Violation{{Pointer: "/" + strings.ReplaceAll(typeErr.Field, ".", "/"), Detail: "must be " + typeErr.Type.String()}}
return p
}
return problem.New(http.StatusBadRequest, "malformed-body", "Malformed request body", err.Error())
}
// encode writes v as JSON with status.
func encode[T any](w http.ResponseWriter, status int, v T) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(v)
}404 and 405 as Problem Details Important
ServeMux answers unmatched requests itself with plain text: 404 for an unknown path and, since Go 1.22, "a 405 Method Not Allowed error that lists the available methods in an Allow header" for a known path with another method. Registering a catch-all "/" to customise this would also swallow the 405s, because "/" matches every method. problemFallback asks mux.Handler(r) for the pattern first; an empty pattern means the mux would answer itself, so the fallback runs that answer into a recorder, keeps the Allow header and status, and writes a Problem Details body instead. Matched requests go through mux.ServeHTTP so r.PathValue and r.Pattern are set (they are not set by mux.Handler).
DELETE /v1/products (registered: GET, POST)
1 mux.Handler(r) -> (405 handler, pattern "")
2 recorder: status 405, Allow: GET, HEAD, POST
3 problem.Write 405 about:blank "Method Not Allowed" + Allow header (real output in the Lab)Keyset SQL and the indexes it needs Must-know
The row-value comparison (price_cents, id) < ($3, $4) is evaluated as the PostgreSQL manual describes for row constructor comparison: "the row elements are compared left-to-right, stopping as soon as an unequal or null pair of elements is found", which is exactly "after the last row in (price_cents, id) order". With an index on (price_cents, id) PostgreSQL can seek to the position and read LIMIT rows, so page 1,000 costs the same as page 1. pgrepo.BuildList produces this SQL (asserted by TestBuildListKeysetDesc):
-- schema (pgrepo.Schema): one composite index per allowed sort
CREATE TABLE products (
id text PRIMARY KEY,
sku text NOT NULL UNIQUE,
name text NOT NULL,
price_cents bigint NOT NULL CHECK (price_cents >= 0),
currency char(3) NOT NULL,
status text NOT NULL,
tags jsonb NOT NULL DEFAULT '[]',
version bigint NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL
);
CREATE INDEX products_price_id ON products (price_cents, id);
-- page 2 of GET /v1/products?status=active&min_price=500&sort=-price&limit=20
SELECT id, sku, name, price_cents, currency, status, version, created_at, updated_at
FROM products
WHERE status = 'active' AND price_cents >= 500
AND (price_cents, id) < (1999, 'prd_42')
ORDER BY price_cents DESC, id DESC
LIMIT 21;
-- the offset version reads and discards 20,000 rows to return 20
SELECT * FROM products ORDER BY price_cents DESC, id DESC LIMIT 20 OFFSET 20000;
-- optimistic concurrency: a stale writer updates 0 rows
UPDATE products SET price_cents = 1200, version = 2, updated_at = now()
WHERE id = 'prd_42' AND version = 1;
-- idempotency keys shared by all instances
CREATE TABLE idempotency_keys (
scope text PRIMARY KEY, -- 'POST /v1/products <key>'
fingerprint text NOT NULL,
status int, -- NULL while in flight
response bytea,
created_at timestamptz NOT NULL DEFAULT now()
);
INSERT INTO idempotency_keys (scope, fingerprint) VALUES ($1, $2) ON CONFLICT DO NOTHING;Exact responses (real run) Important
| Situation | Status line | Body (abridged) |
|---|---|---|
| Create | HTTP/1.1 201 Created, Etag: "v1", Location: /v1/products/prd_fc89a65f13439790 | The product, "version":1 |
| Retry with same key | HTTP/1.1 201 Created, Idempotent-Replayed: true | Identical body |
| Validation | HTTP/1.1 422 Unprocessable Entity | "type":"https://api.example.test/problems/validation", five errors |
Conditional GET (If-None-Match: W/"v1") | HTTP/1.1 304 Not Modified | None |
If-Match: "v1", "v2" against v2 | HTTP/1.1 200 OK, Etag: "v3" | The product |
| Stale If-Match | HTTP/1.1 412 Precondition Failed | "type":".../stale-version" |
| No If-Match | HTTP/1.1 428 Precondition Required | "type":".../if-match-required" |
| Wrong method | HTTP/1.1 405 Method Not Allowed, Allow: GET, HEAD, POST | "type":"about:blank","title":"Method Not Allowed" |
| Cursor reused with other sort | 400 | "detail":"cursor: invalid or does not match the current filter and sort" |
limit=-1 | 400 | "detail":"limit: must not be negative" |
| Readiness while draining | 503 | "detail":"shutting down" |
Note that Go's status line still says "Unprocessable Entity" (http.StatusText(422)), while RFC 9110 renamed 422 "Unprocessable Content"; clients must use the number. Etag and X-Request-Id appear in canonical header form (textproto.CanonicalMIMEHeaderKey); header names are case-insensitive.
Solving the classic problems
| Problem | Symptom | Solution | Cost |
|---|---|---|---|
| Errors as 200 | Clients parse strings; retries and alerts blind | RFC 9457 + real status codes, one writeError | One package |
| Mass assignment | Client sets version, id, is_admin | Write DTO + DisallowUnknownFields | Mapping code |
| Unbounded bodies | Memory spikes, slow-loris uploads | MaxBytesReader → 413, server timeouts | A limit per route |
| Lost update | Edits silently erased | ETag + If-Match → 412/428, WHERE version = ? | Clients send a header |
| Duplicate creates on retry | Two orders, two charges | Idempotency-Key with fingerprint and replay | A key store |
| Page drift and slow deep pages | Duplicates while scrolling; page 10,000 slow | Keyset cursor + composite index + Link | No random page access |
| Sort/filter injection | SQL injection, table scans | Allow-list → column map, typed filters | One map |
| Spec drift | Docs and clients wrong | Contract test, or generate from the spec | One test |
| Leaking internals | Stack traces, SQL in errors | Generic 500 + request ID; cause only in logs | None |
| Dropped requests on deploy | 502 bursts | readyz flip, drain delay, Shutdown with timeout | Seconds per deploy |
Untestable main | Wiring bugs found in staging | Run(ctx, args, getenv, stdout); constructors | None |
Lost update: the fix in three places
The Before test TestLostUpdate shows a price change erased by a later name change from a stale client. The fix needs all three parts: the handler requires If-Match (428 without it), the service compares versions (fast path, 412), and the repository repeats the check atomically in SQL (UPDATE ... WHERE version = $9), because two requests can pass the service check at the same moment.
Page drift
TestOffsetPagingRepeatsRows (Before) and TestOffsetDriftVsKeyset (pagination) reproduce the duplicate; TestKeysetWalkVisitsEveryRowOnce walks 25 rows with five-way ties on price in pages of 7 and asserts each row appears once, which is what the id tie-breaker buys.
Duplicate POST
TestRetryIsReplayed runs the handler once for two identical requests; TestStatusCodesFromTheDraft covers 400 (missing key), 409 (retry while the first runs) and 422 (same key, different body); TestServerErrorsAreNotStored shows a 503 is retryable with the same key. Across instances, replace the in-memory map with the idempotency_keys table above.
Spec drift
TestContractMatchesRoutes compares openapi.json with httpapi.Routes(). It does not check schemas; for that, validate responses in tests against the document with kin-openapi's openapi3filter, or move to generated code.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| Small internal API, one team | ServeMux + hand-written DTOs + this structure | Contract test against a hand-written spec | No generator to maintain |
| Public API, many client languages | Spec-first, oapi-codegen strict server | Generated clients, breaking-change check in CI | The document is the product |
| Existing Gin/Echo codebase needs docs | swaggo/swag | Keep annotations next to handlers; CI regenerates | Lowest effort, Swagger 2.0 output |
| Hot paths, strict typing | ogen | Generated JSON and validation | No reflection |
| Code-first with OpenAPI 3.1 at runtime | huma | Its validation from Go types | Spec from types, no comments |
| Validation rules mostly simple | Hand-written Valid(ctx) | One Violation type | No dependency, clear errors |
| Many fields, many rules | go-playground/validator | RegisterTagNameFunc, own messages | Less code |
| Lists that grow or change | Keyset cursor | Encrypted opaque token, Link | Stable and fast |
| Admin tables with page numbers | Offset with a cap | Total only when cheap | Users want "page 3 of 9" |
| Any update by more than one actor | ETag + If-Match | 428 when missing | No lost updates |
| Any POST that a client may retry | Idempotency-Key | Shared store, fingerprint | No duplicates |
| Breaking change | /v2 routes + DTOs | Deprecation (RFC 9745) and Sunset (RFC 8594) headers on v1 | Old clients keep working |
| Error format | RFC 9457 | errors[] with JSON Pointers, request_id | A standard clients can share |
In architecture: from a single process to a distributed system
Monolith: one process, one database
The structure on this page is already the right monolith: one binary, Run as the composition root, a ServeMux with every route in one table, a service per aggregate, a repository per aggregate backed by one PostgreSQL database. Uniqueness is a UNIQUE constraint, optimistic concurrency is a version column, idempotency keys are a table, keyset pagination uses composite indexes, and one transaction can cover the business change, the stored idempotent response and an outbox row. Example: a shop backend with products, orders and customers, each with its own service and Repository, all in one process; a new POST /v1/orders writes the order and the stored response for its Idempotency-Key in one transaction, so a crash between them cannot create an order whose retry creates another.
Modular monolith and multiple databases
Packages become modules with explicit APIs: catalog, ordering, billing, each with its own service, repository interface and tables (or schema), and no module reading another's tables. The HTTP layer stays one NewServer, but each module contributes its own routes table, and the OpenAPI document is assembled from per-module fragments. When ordering needs a product price, it calls catalog's service interface, not its repository. If billing moves to a separate database, the transaction boundary moves with it: an order and its invoice are no longer atomic, so ordering writes an outbox event and billing consumes it idempotently. The contract test still compares one spec with all modules' routes.
Microservices
Each service owns its API, its spec, its database and its versioning policy; the patterns on this page apply per service, and three of them become cross-service contracts. Problem Details give every service the same error shape, so a gateway or BFF can pass errors through or translate them. Idempotency keys are forwarded: when the checkout service calls payments with Idempotency-Key: "order-1007-charge", a retry after a timeout cannot charge twice even though checkout does not know whether the first call succeeded. Request IDs (or W3C traceparent) are forwarded so one customer request can be followed through five services. Example flow: mobile app → POST /v1/orders (key K) → orders service validates and stores the order with K → calls POST /v1/payment-intents on payments with key "order-ID-charge" → payments calls the card network → orders answers 201. If the app retries with K, orders replays its stored 201; if orders retries payments, payments replays its stored response. Generated clients from each service's OpenAPI document replace hand-written HTTP between services, and a breaking-change check in CI stops one team from breaking another. Cursor tokens and ETags stay opaque across the boundary: callers must never parse them. Synchronous chains need timeouts and budgets (see context) and the idempotency design in API Idempotency.
Distributed data: replicas, caches, sharded databases, multi-region
Read replicas break read-your-writes: a client that PATCHes and immediately GETs from a replica may see the old version and an old ETag, then get a 412 on its next write. Fixes: route reads that follow a write to the primary for a few seconds, or return the new representation in the write response (this API does) so the client does not need to read. A cache in front of GET /v1/products/{id} can use the ETag (If-None-Match → 304) and must be invalidated on write; caching lists with cursors is rarely worth it. Keyset pagination is the only pagination that works across shards: each shard returns its next page after the cursor and a merge step takes the first N, while OFFSET 10000 across shards means reading 10,000 rows from every shard. Idempotency stores must be global for the scope of the key (per tenant, per region) or a retry routed to another region creates a duplicate. In multi-region active-active setups, version checks need a single writer per resource (home region) or conflict resolution; an ETag cannot protect against two regions accepting conflicting writes at the same time.
Scaling path: 1×, 10×, 100×
| Load | What changes | API practice |
|---|---|---|
| 1× (one instance) | Everything fits in one process | This page as is; in-memory idempotency store is acceptable only here |
| 10× (several instances behind a load balancer) | Shared state must leave the process | Idempotency keys in PostgreSQL or Redis; readiness + drain delay for rolling deploys; per-key rate limits in a shared store or gateway; limit capped at 100 |
| 100× (many services, heavy lists, partners) | Hot lists, retries, many clients | Keyset everywhere with covering indexes; no totals; generated clients; CDN/ETag for hot reads; versioned contracts with deprecation headers; load shedding before the database (Load Shedding) |
Lab
1. Run the tests (real)
cd docs/snippets/go/rest-api-project/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok academy/rest-api-project/app 1.473s
# ok academy/rest-api-project/before 1.328s
# ok academy/rest-api-project/client 1.385s
# ? academy/rest-api-project/cmd/api [no test files]
# ok academy/rest-api-project/config 1.375s
# ok academy/rest-api-project/dto 1.385s
# ok academy/rest-api-project/httpapi 1.470s
# ok academy/rest-api-project/idempotency 1.361s
# ok academy/rest-api-project/memrepo 1.457s
# ok academy/rest-api-project/mergepatch 1.356s
# ok academy/rest-api-project/openapi 1.382s
# ok academy/rest-api-project/pagination 1.377s
# ok academy/rest-api-project/pgrepo 1.468s
# ok academy/rest-api-project/problem 1.492s
# ok academy/rest-api-project/product 1.483s
# ok academy/rest-api-project/service 1.481s
# ok academy/rest-api-project/validation 1.447s2. Create, retry, validate (real)
Labs 2 to 5 are one shell session, run as written (pipeline/sources/rest-api-project/lab-round1.sh.txt); the output below is that run's, with Date headers removed.
go build -o api ./cmd/api
API_CURSOR_KEY=0123456789abcdef API_ADDR=127.0.0.1:8088 API_DRAIN_DELAY=1s ./api > api.log 2>&1 &
PID=$!
B=http://127.0.0.1:8088
curl -si -X POST $B/v1/products -H 'Content-Type: application/json' \
-H 'Idempotency-Key: "8e03978e-40d5-43e8-bc93-6894a57f9324"' -H 'X-Request-ID: lab-1' \
-d '{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"draft","tags":["kitchen"]}' | tee create.txt
# HTTP/1.1 201 Created
# Content-Type: application/json
# Etag: "v1"
# Location: /v1/products/prd_fc89a65f13439790
# X-Request-Id: lab-1
# {"id":"prd_fc89a65f13439790","sku":"MUG-1","name":"Mug","price_cents":900,...,"tags":["kitchen"],"version":1,...}
LOC=$(grep -i '^Location:' create.txt | tr -d '\r' | cut -d' ' -f2) # /v1/products/prd_fc89a65f13439790
# the same POST again (a retry)
# HTTP/1.1 201 Created
# Etag: "v1"
# Idempotent-Replayed: true
# Location: /v1/products/prd_fc89a65f13439790 same product, nothing created
# X-Request-Id: 67fea3ffd3cdc8b3 the retry's own request id
curl -si -X POST $B/v1/products -H 'Content-Type: application/json' -H 'X-Request-ID: lab-2' \
-d '{"sku":"AB","name":"","currency":"eur","status":"sold"}'
# HTTP/1.1 422 Unprocessable Entity
# Content-Type: application/problem+json
# {"type":"https://api.example.test/problems/validation","title":"Request body failed validation",
# "status":422,"instance":"/v1/products","errors":[{"pointer":"/sku","detail":"must be at least 3"},
# {"pointer":"/name","detail":"is required"},{"pointer":"/price_cents","detail":"is required"},
# {"pointer":"/currency","detail":"must be upper case"},
# {"pointer":"/status","detail":"must be one of: draft active archived"}],"request_id":"lab-2"}3. Conditional requests and merge patch (real)
curl -si $B$LOC -H 'If-None-Match: W/"v1"' # weak comparison
# HTTP/1.1 304 Not Modified
# Etag: "v1"
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' \
-H 'If-Match: "v1"' -d '{"price_cents":1200,"status":"active","tags":null}'
# HTTP/1.1 200 OK
# Etag: "v2"
# {...,"price_cents":1200,"currency":"EUR","status":"active","tags":[],"version":2,...}
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' -H 'If-Match: "v1"' -d '{"name":"Cup"}'
# HTTP/1.1 412 Precondition Failed
# {"type":"https://api.example.test/problems/stale-version","title":"Resource changed since you read it",
# "status":412,"detail":"GET it again and retry with the new ETag in If-Match",...}
curl -si -X PATCH $B$LOC -H 'Content-Type: application/merge-patch+json' -H 'If-Match: "v1", "v2"' -d '{"name":"Cup"}'
# HTTP/1.1 200 OK any listed tag may match
# Etag: "v3"
curl -si -X PUT $B$LOC -H 'Content-Type: application/json' \
-d '{"sku":"MUG-1","name":"Mug","price_cents":900,"currency":"EUR","status":"active"}'
# HTTP/1.1 428 Precondition Required
curl -si -X DELETE $B/v1/products
# HTTP/1.1 405 Method Not Allowed
# Allow: GET, HEAD, POST
# {"type":"about:blank","title":"Method Not Allowed","status":405,"instance":"/v1/products",...}4. Follow the cursor (real)
for i in 1 2 3 4; do
curl -s -o /dev/null -X POST $B/v1/products -H 'Content-Type: application/json' \
-d "{\"sku\":\"SKU-$i\",\"name\":\"Item $i\",\"price_cents\":${i}00,\"currency\":\"EUR\",\"status\":\"active\"}"
done # prices 100..400, plus MUG-1 at 1200
curl -si "$B/v1/products?sort=price&limit=2" > page1.txt
# HTTP/1.1 200 OK
# Link: </v1/products?cursor=KBODNt5ZckjAnijDw1_9e3s2yLMDLQPX37Ojh8Z0TaSJB58GbwO6lb1Zo3BxbdpQF5QqDTHDZluAkmB_EJqzwImqXQaAvbbij9Eq9f06UNoFXun5xA&limit=2&sort=price>; rel="next"
# page 1: SKU-1, SKU-2 has_more: true
NEXT=$(tail -1 page1.txt | python3 -c 'import sys,json;print(json.load(sys.stdin)["next_cursor"])')
curl -s "$B/v1/products?sort=price&limit=2&cursor=$NEXT"
# page 2: SKU-3, SKU-4 has_more: true (page 3 would hold MUG-1)
curl -s "$B/v1/products?sort=name&limit=2&cursor=$NEXT"
# {"type":".../invalid-query","status":400,"detail":"cursor: invalid or does not match the current filter and sort",...}The token is base64url of a random nonce and an AES-GCM ciphertext: decoding it shows no product id, price or query.
5. Graceful shutdown (real)
kill -TERM $PID
sleep 0.3 # inside the 1 s drain delay
curl -s $B/readyz
# {"type":"about:blank","title":"Service Unavailable","status":503,"detail":"shutting down",...}
wait $PID; echo "exit=$?"
# exit=0
grep -E '"shutting down"|/readyz.*503|"stopped"' api.log
# {"level":"INFO","msg":"shutting down","drain_delay":"1s","timeout":"10s"}
# {"level":"INFO","msg":"request","path":"/readyz","pattern":"GET /readyz","status":503,...}
# {"level":"INFO","msg":"stopped"}6. Generate a server with oapi-codegen (expected, not run)
The generated code needs Go 1.26+, so it is not part of the go 1.24 snippet module. In a separate module with go 1.26:
go get -tool github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen@v2.9.0
cat > oapi-codegen.yaml <<'YAML'
package: api
output: api/api.gen.go
generate:
std-http-server: true
strict-server: true
models: true
client: true
YAML
go tool oapi-codegen -config oapi-codegen.yaml openapi.json
# expected: api/api.gen.go with ServerInterface, StrictServerInterface, HandlerFromMux,
# ProductWrite/Product/Problem models and ClientWithResponses7. Run the repository against PostgreSQL (expected, not run)
Apply pgrepo.Schema, open a pool with pgx's database/sql adapter (sql.Open("pgx", dsn) after importing github.com/jackc/pgx/v5/stdlib), pass pgrepo.New(db) instead of memrepo.New() in Run (it compiles as is: repo is typed as service.Repository plus Ping), and run EXPLAIN on the keyset query from Mechanics: the expected plan is an Index Scan Backward using products_price_id, with no Sort node, and the same cost for page 1 and page 1,000. The offset query's plan reads OFFSET + LIMIT rows.
For PHP/Laravel developers
Laravel gives you most of this page by convention. Route::apiResource('photos', PhotoController::class) registers the five API routes and leaves out create and edit; a Form Request (php artisan make:request StorePostRequest) holds rules() and authorize(), and a failed validation on a request expecting JSON becomes a 422 with {"message": ..., "errors": {...} }; API Resources are "a transformation layer that sits between your Eloquent models and the JSON responses", with toArray, whenLoaded to avoid N+1, the outermost resource "wrapped in a data key" (disable with JsonResource::withoutWrapping()), and links/meta added for paginated collections. Laravel 13 also ships JSON:API resources. paginate, simplePaginate and cursorPaginate map to offset with total, offset without total, and keyset ("cursor pagination works by constructing "where" clauses that compare the values of the ordered columns contained in the query"). What Laravel does not give you by default: Problem Details, ETag/If-Match, Idempotency-Key handling and an OpenAPI document; those are packages or your own middleware, as in Go.
// routes/api.php: Route::apiResource('products', ProductController::class);
public function store(StoreProductRequest $request): JsonResponse // rules() run first: 422 on failure
{
$product = Product::create($request->validated()); // only validated fields: no mass assignment
return (new ProductResource($product))->response()->setStatusCode(201); // response() returns Illuminate\Http\JsonResponse
}
public function index(Request $request)
{
return ProductResource::collection(
Product::where('status', 'active')->orderBy('price_cents')->orderBy('id')->cursorPaginate(20)
); // {"data":[...],"links":{...},"meta":{...}}
}| Laravel | Go (this chapter) |
|---|---|
Route::apiResource('products', ...) | Routes table with Go 1.22 patterns |
Form Request rules() + validated() | dto.ProductWrite + Valid(ctx) or validator tags |
422 {"message","errors":{"field":[...]} } | 422 RFC 9457 with errors[] and JSON Pointers |
API Resource toArray, whenLoaded | dto.View(p) mapping function |
data wrapping, links, meta | ListView{data, next_cursor, has_more} + Link header |
cursorPaginate(20) | pgrepo.BuildList keyset + encrypted cursor |
| Service container, auto-wiring | Constructors called in Run |
.env + config() | config.Load(getenv) |
php artisan serve, FPM | Run + http.Server + Shutdown |
| Community packages generate OpenAPI | Hand-written spec + drift test, or oapi-codegen |
Common misconceptions
| Belief | Reality |
|---|---|
| REST means one endpoint per table | Resources are what clients reason about; actions with rules can be sub-resources |
200 with {"error": ...} is fine if the client checks the body | Proxies, retry libraries, SDKs and alerts read the status; use 4xx/5xx and RFC 9457 |
| Clients should parse the error message | RFC 9457: consumers SHOULD NOT parse detail; switch on type |
| Decoding into the domain struct saves code | It enables mass assignment and leaks internals; use DTOs |
json.Decoder rejects unknown fields by default | Only after DisallowUnknownFields(); the body is also unbounded until MaxBytesReader |
| Validation and business rules are the same | Shape errors are 422 without I/O; state rules are 409 in the service or database |
| Offset pagination is fine for small tables | It still duplicates or skips rows when data changes between pages |
| Base64 or a signature makes a cursor opaque | Base64 is readable and a signature only stops edits; AIP-158 asks for tokens clients cannot parse, so encrypt (AES-GCM here) |
PATCH should decode into a struct and copy non-zero fields | Cannot express zero or removal; apply RFC 7396 to the JSON, then validate |
| Database transactions prevent lost updates | Not across two HTTP requests; use ETag + If-Match + a version check |
| A unique constraint makes POST retries safe | It turns retries into 409s; an Idempotency-Key replays the first answer |
| swag produces OpenAPI 3 | Stable swag emits Swagger 2.0; 3.1 only in the v2 release candidates |
srv.Shutdown() finishes everything | It waits only for active connections, forever unless its ctx has a deadline; fail readiness first |
| Liveness should check the database | A database outage would restart every pod; check dependencies in readiness |
| Go needs a DI container | Constructors called from one Run function are checked by the compiler |
Cheat sheet
| Topic | Remember |
|---|---|
| Plan first | Resources, URLs, operation table, status codes, then openapi.json, then code |
| Routes | One table; Go 1.22 "METHOD /v1/products/{id}", r.PathValue("id") |
| Handlers | Maker functions take dependencies, return http.Handler |
| Decode | Content-Type → MaxBytesReader → DisallowUnknownFields → one value → Valid(ctx) |
| Errors | application/problem+json, type URI, same status in header and body, errors[] with pointers |
| Codes | 400 malformed · 422 invalid · 409 conflict · 412 stale · 428 no If-Match · 429 limited |
| Layers | handler → service (owns Repository) → repo; domain errors mapped in one writeError |
| Wiring | main calls Run(ctx, args, getenv, stdout); constructors only; no globals |
| Config | config.Load(getenv), all errors at once with errors.Join |
| Pagination | Keyset (col, id), limit+1, encrypted opaque token bound to filter and sort, Link: rel="next" |
| Filter/sort | Typed params, allow-listed sort → column map, index per sort |
| PATCH | application/merge-patch+json; null deletes; arrays replaced; re-validate |
| Concurrency | ETag from version; If-Match required; WHERE version = ? |
| Idempotency | Idempotency-Key + body fingerprint; replay; 409 in flight; 422 reused |
| Versioning | /v1 for breaking changes only; Deprecation and Sunset headers before removal |
| Contract | OpenAPI 3.1 embedded and served; test routes against it; Scalar or Swagger UI at /docs |
| Tests | httptest.NewServer + in-memory repo; Run end to end; t.Context() |
| Shutdown | readyz 503 → drain delay → Shutdown(ctx with timeout) → wait for ErrServerClosed |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why should a validation failure not return 200 with an error field, and which status and body does this API return instead? Must-know
Answer
Answer: Clients, proxies, retry libraries, SDK generators and alerting read the status code first; a 200 makes the failure invisible to all of them. The API returns 422 with Content-Type: application/problem+json, a type URI for the validation problem, and an errors array with one JSON Pointer per invalid field (see Problem Details).
2 — What is the difference between 400, 422 and 409 in this API? Must-know
Answer
Answer: 400 means the bytes could not be turned into the request type (malformed JSON, unknown field, wrong JSON type, bad query parameter). 422 means the JSON decoded but the values break the rules of the request (negative price). 409 means the request is valid but conflicts with stored state (duplicate SKU, archived product re-activated, same idempotency key still in flight).
3 — Why decode into a DTO instead of the domain type, and what does DisallowUnknownFields add? Must-know
Answer
Answer: A DTO contains only client-writable fields, so a client cannot set id or version (mass assignment), and new domain fields do not leak into the contract. DisallowUnknownFields turns a misspelled or forbidden member into a 400 instead of silently ignoring it, which also catches clients sending read-only fields in a merge patch.
4 — Explain why OFFSET pagination shows a row twice when a new row is inserted, and how keyset pagination avoids it. Must-know
Answer
Answer: OFFSET 20 means "skip the first 20 rows of the current result"; an insert at the head shifts every row down by one, so the 20th row of page 1 becomes the 21st and is returned again on page 2. Keyset pagination asks for rows after the last seen key, WHERE (sort_col, id) > (last_value, last_id), which does not depend on how many rows exist before it, and an index on (sort_col, id) makes every page a seek.
5 — Why must the cursor include a tie-breaker and be opaque? Important
Answer
Answer: Sorting by price alone is not a total order; rows with equal prices would be skipped or repeated across page boundaries, so id is appended to the sort and to the cursor. Opaque tokens (here AES-GCM encrypted, because base64 or a signature alone can still be read) keep the scheme out of the contract (AIP-158: "must not be user-parseable") and stop clients from editing positions; binding the token to the filter and sort makes reuse with another query a clean 400.
6 — How does ETag + If-Match prevent a lost update, and when does the API return 412 vs 428? Must-know
Answer
Answer: The ETag carries the resource version; a write must send it back in If-Match, and the server performs the write only if it still matches (UPDATE ... WHERE version = ?). A stale tag gets 412 Precondition Failed; a write with no If-Match at all gets 428 Precondition Required (RFC 6585), so clients cannot skip the check by omission.
7 — Why does PATCH apply RFC 7396 to the JSON document instead of decoding the patch into a struct? Important
Answer
Answer: A struct cannot distinguish "absent", null and the zero value, so a struct-based patch cannot set a price to 0 or remove a list. Merge patch works on the JSON: present members are set, null deletes, absent members stay; the merged document is then decoded and validated exactly like a PUT, so both paths share one set of rules.
8 — A client times out on POST /v1/products and retries. What makes the retry safe, and what are the 409 and 422 cases? Must-know
Answer
Answer: The Idempotency-Key header: the server stores the first final response under that key and replays it (same status, Location and body) for retries with the same body. A retry that arrives while the first request is still running gets 409; the same key with a different body gets 422, as in the IETF draft.
9 — What is the run function pattern, and why does it help testing? Important
Answer
Answer: main only calls Run(ctx, args, getenv, stdout) error, which builds every dependency and serves until the context is canceled. Because the operating system is passed in, a test can start the real program in a goroutine with fake env and flags, wait for /readyz, drive it over HTTP and cancel the context to test graceful shutdown, in parallel with other tests.
10 — Where should the Repository interface be declared in Go, and why one per aggregate rather than a generic one? Important
Answer
Answer: In the consumer, the service package, so the service states exactly what it needs and implementations depend on it, not the reverse. One interface per aggregate speaks domain operations and errors (keyset List, Update with an expected version); a generic Repository[T] pushes query building back into the service and cannot express those operations cleanly.
11 — Compare swaggo/swag, oapi-codegen and ogen in one sentence each. Important
Answer
Answer: swaggo/swag is code-first: it generates a Swagger 2.0 document from comments (OpenAPI 3.1 only in its v2 release candidates). oapi-codegen is spec-first: from OpenAPI 3.0/3.1 it generates server interfaces (including a strict server) for net/http and common routers, models and clients. ogen is spec-first too and generates everything including JSON encoding, validation and a router, without reflection.
12 — Describe a graceful shutdown that loses no requests behind a load balancer. Good to know
Answer
Answer: On SIGTERM, make /readyz return 503, wait a drain delay long enough for the load balancer to stop routing to the instance, then call srv.Shutdown with a deadline so the listener closes and in-flight requests finish, and wait for Serve to return http.ErrServerClosed before exiting. Liveness stays independent of dependencies throughout.
13 — Why does this API keep the ServeMux 405 behaviour instead of registering a catch-all "/" handler for JSON 404s? Good to know
Answer
Answer: A "/" pattern matches every method and path, so a request with a wrong method on a known path would hit the catch-all and become a 404, losing the 405 and its Allow header. The fallback asks mux.Handler(r) for the pattern and only rewrites the mux's own 404/405 replies as problems, keeping Allow.
Glossary
| Term | Meaning |
|---|---|
| REST | Fielding's architectural style: resources, representations, self-descriptive messages, hypermedia |
| Resource | Anything a client can name and address with a URL |
| Resource modelling | Choosing the nouns, fields, lifecycles and ownership the API exposes |
| URL design | Rules for paths: plural collections, opaque IDs, shallow nesting, version prefix |
| Project planning | Writing resources, URLs, operations and rules before code |
| Representation | The JSON a client sends or receives for a resource |
| Handler | Function that turns one request into one response |
| Maker function | Function that receives dependencies and returns an http.Handler |
| Routes table | One list of every pattern and handler: the API surface |
ServeMux pattern | Go 1.22 route syntax "METHOD /path/{wildcard}" |
PathValue | Method returning a wildcard's value from the matched path |
Request.Pattern | Go 1.23 field with the matched pattern, useful as a metric label |
| DTO | Data transfer object: a struct that exists only for the wire format |
| Mass assignment | A client setting fields it should not, through a generic decode or update |
| Request validation | Checking a decoded request's values; failures are 422 |
| go-playground/validator | Tag-based struct validation library, Gin's default validator |
Valid(ctx) | Hand-written validation method (Mat Ryer's Validator interface) |
| JSON Pointer | RFC 6901 path into a JSON document, such as /tags/2 |
| Error envelope | The single JSON shape every error response uses |
| Problem Details | RFC 9457 error format, application/problem+json |
about:blank | Default problem type: no meaning beyond the status code |
| Extension member | Extra problem field defined by the API (errors, request_id) |
| Status code | Three-digit HTTP result class and meaning |
| 412 Precondition Failed | A conditional header such as If-Match did not match |
| 428 Precondition Required | The server requires a conditional request (RFC 6585) |
| 422 Unprocessable Content | Well-formed request with invalid content (RFC 9110 name) |
| Repository pattern | Collection-like interface that hides storage for one aggregate |
| Aggregate | Cluster of domain objects treated as one unit for changes |
| Interface per aggregate | A repository interface shaped by one aggregate's use cases |
| Service layer | Use cases and state-dependent rules, independent of transport |
| Dependency injection via constructors | Passing every dependency into New... functions |
| Composition root | The one place that builds all concrete objects (Run) |
| Run function pattern | main calls run(ctx, args, getenv, stdout) error (Mat Ryer) |
| Configuration via env | Twelve-factor: deploy-specific settings from environment variables |
| Pagination | Returning a collection in pages |
| Offset pagination | LIMIT n OFFSET k: skip k rows |
| Keyset pagination | WHERE (col, id) > (last): continue after the last seen key |
| Cursor | Opaque token encoding the position for the next page |
next_cursor | Response field carrying the cursor for the following page |
| Link header | RFC 8288 header, here rel="next" with the next page URL |
| Filtering | Narrowing a collection with typed query parameters |
| Sorting | Ordering a collection by an allow-listed field, - for descending |
| PATCH | RFC 5789 method applying a set of changes to a resource |
| JSON Merge Patch | RFC 7396 patch format; null deletes, arrays replaced |
| JSON Patch | RFC 6902 list of operations (add, remove, replace, ...) |
| ETag | Entity tag: identifier of a representation's version |
| If-Match | Conditional header: perform the write only if the ETag matches |
| If-None-Match | Conditional header: return 304 if the ETag still matches |
| Strong comparison | ETag matching that rejects weak tags, required for If-Match |
| Optimistic concurrency | Detecting conflicting writes by version instead of locking |
| Lost update | One client's write silently overwriting another's |
| Idempotency key | Client-chosen key that makes a non-idempotent request safe to retry |
| Fingerprint | Hash of the request body stored with the idempotency key |
| Versioning | Running incompatible API contracts side by side (/v1, /v2) |
| Deprecation / Sunset headers | RFC 9745 / RFC 8594 headers announcing retirement |
| OpenAPI 3.1 | API description format aligned with JSON Schema 2020-12 |
| Swagger 2.0 | Predecessor of OpenAPI 3, still emitted by swaggo/swag v1 |
| swaggo/swag | Code-first generator of Swagger documents from Go comments |
| oapi-codegen | Spec-first generator of Go servers, models and clients |
| ogen | Spec-first generator with generated JSON, validation and router |
| Strict server | oapi-codegen mode with typed request and response objects |
| Generated client | Typed client code produced from an OpenAPI document |
| Contract test | Test that the running routes match the published spec |
| Swagger UI | Interactive OpenAPI reference page (swagger-ui-dist) |
| Scalar | Interactive OpenAPI reference loaded from one HTML page |
| httptest | Go package with NewServer and NewRecorder for HTTP tests |
| End-to-end test | Test through the real handler stack or the whole program |
| In-memory repository | Map-backed implementation of the repository port for tests |
| Graceful shutdown | Stop accepting, finish in-flight requests, then exit |
| Drain delay | Pause between failing readiness and closing the listener |
| Liveness / readiness | Health endpoints: "restart me?" vs "send me traffic?" |
| Structured logging | Key-value log records (log/slog JSON) |
| Request ID | Identifier correlating one request across logs and responses |
| Rate limiting hook | Middleware slot that can reject requests with 429 |
| Laravel API Resources | Laravel's transformation layer from models to JSON |
| Form Request | Laravel request class with rules() and authorize() |
References
- Mat Ryer, "How I write HTTP services in Go after 13 years", Grafana Labs blog, 2024: https://grafana.com/blog/2024/02/09/how-i-write-http-services-in-go-after-13-years/
- Roy T. Fielding, "Architectural Styles and the Design of Network-based Software Architectures", 2000, chapter 5: https://ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm
- RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457.txt
- RFC 7807, Problem Details (obsoleted): https://www.rfc-editor.org/rfc/rfc7807.txt
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110.txt
- RFC 5789, PATCH Method for HTTP: https://www.rfc-editor.org/rfc/rfc5789.txt
- RFC 7396, JSON Merge Patch: https://www.rfc-editor.org/rfc/rfc7396.txt
- RFC 6902, JSON Patch: https://www.rfc-editor.org/rfc/rfc6902.txt
- RFC 6901, JSON Pointer: https://www.rfc-editor.org/rfc/rfc6901.txt
- RFC 6585, Additional HTTP Status Codes (428, 429): https://www.rfc-editor.org/rfc/rfc6585.txt
- RFC 8288, Web Linking: https://www.rfc-editor.org/rfc/rfc8288.txt
- RFC 8594, The Sunset HTTP Header Field: https://www.rfc-editor.org/rfc/rfc8594.txt
- RFC 9745, The Deprecation HTTP Response Header Field: https://www.rfc-editor.org/rfc/rfc9745.txt
- RFC 9651, Structured Field Values for HTTP: https://www.rfc-editor.org/rfc/rfc9651.txt
- IETF draft, The Idempotency-Key HTTP Header Field: https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header
- IETF draft, RateLimit header fields for HTTP: https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-ratelimit-headers
- OpenAPI Specification 3.1.0: https://spec.openapis.org/oas/v3.1.0.html
- OpenAPI Specification 3.1.1: https://spec.openapis.org/oas/v3.1.1.html
- OpenAPI Specification 3.0.3: https://spec.openapis.org/oas/v3.0.3.html
- OpenAPI Specification, latest: https://spec.openapis.org/oas/latest.html
- swaggo/swag README: https://raw.githubusercontent.com/swaggo/swag/master/README.md
- swaggo/swag v2 README: https://raw.githubusercontent.com/swaggo/swag/v2/README.md
- swaggo/http-swagger README: https://raw.githubusercontent.com/swaggo/http-swagger/master/README.md
- oapi-codegen README: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/README.md
- oapi-codegen net/http server docs: https://raw.githubusercontent.com/oapi-codegen/oapi-codegen/main/docs/stdhttp-server.md
- ogen README: https://raw.githubusercontent.com/ogen-go/ogen/main/README.md
- kin-openapi README: https://raw.githubusercontent.com/getkin/kin-openapi/master/README.md
- huma README: https://raw.githubusercontent.com/danielgtaylor/huma/main/README.md
- go-playground/validator README: https://raw.githubusercontent.com/go-playground/validator/master/README.md
- go-playground/validator doc.go: https://raw.githubusercontent.com/go-playground/validator/master/doc.go
- pgx
PgError.SQLState: https://raw.githubusercontent.com/jackc/pgx/master/pgconn/errors.go - lib/pq
Error.SQLState: https://raw.githubusercontent.com/lib/pq/master/error.go - Google wire README: https://raw.githubusercontent.com/google/wire/main/README.md
- Uber fx README: https://raw.githubusercontent.com/uber-go/fx/master/README.md
- Uber fx
fxtest: https://raw.githubusercontent.com/uber-go/fx/master/fxtest/app.go - Uber dig README: https://raw.githubusercontent.com/uber-go/dig/master/README.md
- sqlc README: https://raw.githubusercontent.com/sqlc-dev/sqlc/main/README.md
- GORM README: https://raw.githubusercontent.com/go-gorm/gorm/master/README.md
- ent README: https://raw.githubusercontent.com/ent/ent/master/README.md
- caarlos0/env README: https://raw.githubusercontent.com/caarlos0/env/main/README.md
- kelseyhightower/envconfig README: https://raw.githubusercontent.com/kelseyhightower/envconfig/master/README.md
- evanphx/json-patch README: https://raw.githubusercontent.com/evanphx/json-patch/master/README.md
- Scalar: https://github.com/scalar/scalar
- Swagger UI README: https://raw.githubusercontent.com/swagger-api/swagger-ui/master/README.md
- Go module proxy, validator v10.30.1 go.mod: https://proxy.golang.org/github.com/go-playground/validator/v10/@v/v10.30.1.mod
- Go module proxy, oapi-codegen v2.9.0 go.mod: https://proxy.golang.org/github.com/oapi-codegen/oapi-codegen/v2/@v/v2.9.0.mod
- Go module proxy, ogen v1.25.0 go.mod: https://proxy.golang.org/github.com/ogen-go/ogen/@v/v1.25.0.mod
- Go module proxy, swag v2 versions: https://proxy.golang.org/github.com/swaggo/swag/v2/@v/list
- Go tutorial, "Developing a RESTful API with Go and Gin": https://go.dev/doc/tutorial/web-service-gin
- Go blog, "Routing Enhancements for Go 1.22": https://go.dev/blog/routing-enhancements
- Go 1.20 release notes (
errors.Join): https://go.dev/doc/go1.20 - Go 1.21 release notes: https://go.dev/doc/go1.21
- Go 1.22 release notes: https://go.dev/doc/go1.22
- Go 1.23 release notes: https://go.dev/doc/go1.23
- Go 1.24 release notes: https://go.dev/doc/go1.24
- Go 1.25 release notes: https://go.dev/doc/go1.25
- Go 1.26 release notes: https://go.dev/doc/go1.26
- Go 1.27 release notes: https://go.dev/doc/go1.27
net/httpserver source (Shutdown,ServeMux): https://go.dev/src/net/http/server.gonet/httprequest source (MaxBytesReader,PathValue): https://go.dev/src/net/http/request.gonet/httpstatus codes: https://go.dev/src/net/http/status.gonet/http/httptestserver: https://go.dev/src/net/http/httptest/server.goencoding/jsonstream (DisallowUnknownFields): https://go.dev/src/encoding/json/stream.goos/signal(NotifyContext): https://go.dev/src/os/signal/signal.go- Google AIP-122, Resource names: https://google.aip.dev/122
- Google AIP-132, Standard methods: List: https://google.aip.dev/132
- Google AIP-134, Standard methods: Update: https://google.aip.dev/134
- Google AIP-154, Resource freshness validation (etags): https://google.aip.dev/154
- Google AIP-158, Pagination: https://google.aip.dev/158
- Google AIP-160, Filtering: https://google.aip.dev/160
- Google AIP-185, API Versioning: https://google.aip.dev/185
- Google AIP-193, Errors: https://google.aip.dev/193
- Stripe API, Pagination: https://docs.stripe.com/api/pagination
- Stripe API, Idempotent requests: https://docs.stripe.com/api/idempotent_requests
- Stripe API, Errors: https://docs.stripe.com/api/errors
- Stripe API, Versioning: https://docs.stripe.com/api/versioning
- GitHub REST, Using pagination: https://docs.github.com/en/rest/using-the-rest-api/using-pagination-in-the-rest-api
- GitHub REST, API versions: https://docs.github.com/en/rest/about-the-rest-api/api-versions
- JSON:API specification: https://jsonapi.org/format/
- JSON:API cursor pagination profile: https://jsonapi.org/profiles/ethanresnick/cursor-pagination/
- Markus Winand, "No Offset": https://use-the-index-luke.com/no-offset
- PostgreSQL, Row and array comparisons: https://www.postgresql.org/docs/current/functions-comparisons.html
- PostgreSQL, LIMIT and OFFSET: https://www.postgresql.org/docs/current/queries-limit.html
- PostgreSQL, Multicolumn indexes: https://www.postgresql.org/docs/current/indexes-multicolumn.html
- The Twelve-Factor App, Config: https://12factor.net/config
- Kubernetes, Liveness, Readiness and Startup Probes: https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
- Kubernetes, API health endpoints: https://kubernetes.io/docs/reference/using-api/health-checks/
- Laravel 13, Eloquent API Resources: https://laravel.com/docs/13.x/eloquent-resources
- Laravel 13, Validation: https://laravel.com/docs/13.x/validation
- Laravel 13, Pagination: https://laravel.com/docs/13.x/pagination
- Laravel 13, Controllers (
apiResource): https://laravel.com/docs/13.x/controllers