GIN TUTORIAL · GO WEB SERVICES · 9 LESSONS
Gin project: a complete REST API
Layout, dependencies, CRUD, pagination, problem details, idempotency keys, optimistic concurrency, API tests and startup.
Lay out a Gin service so every import points toward the domain
Organize a Gin API into cmd/api, httpapi, notes and store packages whose imports point toward the domain, with all concrete wiring in main.
5 min · Worked lesson
Give Gin handlers their dependencies through a struct, not globals or context keys
Write handlers as methods on a struct built by a constructor, depend on small consumer-defined interfaces and swap in a fake store for tests.
5 min · Worked lesson
Full CRUD on one resource: exact status codes, a Location header and PUT versus PATCH
Implement create, read, replace, patch and delete for notes with correct status codes, a Location header and presence-aware PATCH fields.
5 min · Worked lesson
Paginate with opaque cursors, a bounded limit and a total order; filter only through allow-lists
Serve stable pages of notes with keyset cursors, cap the page size and accept only allow-listed filter and sort parameters.
5 min · Worked lesson
One error envelope: RFC 9457 problem details mapped from domain errors in one middleware
Return application/problem+json for every failure by mapping a small domain error taxonomy to HTTP statuses in a single Gin middleware.
5 min · Worked lesson
Make POST safe to retry with Idempotency-Key: fingerprint, reserve, replay and expire
Add Idempotency-Key handling to POST /notes so retries replay the original response, conflicting reuse is rejected and in-flight duplicates wait.
5 min · Worked lesson
Stop lost updates with versions, ETag and If-Match: 428 when missing, 412 when stale
Version the notes resource, expose the version as an ETag and require If-Match on writes so a stale client cannot overwrite a newer edit.
5 min · Worked lesson
Table-driven API tests through the real router: status, headers and JSON compared by meaning
Write table-driven tests that send requests through the real Gin router with fakes and assert status, contract headers and semantically compared JSON bodies.
5 min · Worked lesson
Start from validated configuration and wire the whole service in one composition root
Load and validate configuration from the environment, fail fast with every problem listed, and wire store, service, handlers, engine and http.Server with signal-driven shutdown.
5 min · Worked lesson