Skip to content

Table of Contents

Month 4 · Week 4 — Exercises (capstone: layered REST service)

Standard-library-only Go packages with table-driven tests. They isolate the three layers of the Week 4 project so each can be reasoned about — and tested — on its own.

How to run

go test ./exercises/month-04/week-4/...
# or one at a time:
go test ./exercises/month-04/week-4/service
go test ./exercises/month-04/week-4/httpapi -v

Prompts

  1. service/ — the business-logic layer. Implement Service.Register, which depends only on the consumer-owned Repo interface. Normalise + trim + lower-case the email, validate name length, return wrapped domain errors (ErrInvalid, ErrConflict), and respect a cancelled context.Context. Tests inject a fakeRepo — no database.
  2. httpapi/ — the transport layer. Build an http.Handler (Go 1.22 method+pattern routing) for a notes API over an in-memory Store. Map domain results to status codes (201/400/404/422, plus auto-405). Tests drive it with both httptest.NewRecorder and a real httptest.NewServer.
  3. openapi/ — the contract. Build a valid OpenAPI 3.0 document from a list of Routes. Validate required fields, merge methods onto one path item, lower-case method names, default the success status to 200, and emit deterministic JSON.

Results

Exercise Concept Tests Status
service layered business logic, fake repo, errors.Is, context go test ✅
httpapi handler testing with httptest (recorder + server) go test ✅
openapi OpenAPI 3.0 doc builder, deterministic JSON go test ✅

Key idioms practised: consumer-side interfaces, sentinel errors wrapped with %w and matched via errors.Is, context.Context as the first parameter, and net/http/httptest for fast, hermetic integration tests.