Documentation
¶
Overview ¶
Step 4 of 13: domain errors, mapped to status codes exactly once.
The data functions now return errors in the domain's own language: ErrNotFound and ErrShelfLocked are sentinel values that know nothing about HTTP. One errors.NewOptions() value maps each sentinel to a canonical code (NotFound is 404, PermissionDenied is 403) and app.Use(opts.Handler()) attaches that map to every request. From then on the handlers only forward: ctx.OK(shelf, err) renders the shelf or the mapped error, and ctx.NoContent(true, err) renders 204 or the mapped error. Matching uses errors.Is, so wrapped errors still map. Anything unmapped is a generic 500 whose cause is logged server-side and never sent to the client.
The first business rule arrives with the DELETE route: a locked shelf refuses deletion. The rule lives next to the data, not in the handler, and the handler does not know it exists.
Learn: keep status codes out of your domain, map sentinel errors once, and write handlers that forward errors instead of branching on them. Before: ../03-json-and-validation
Run:
go run main.go
Try:
curl -i -X POST localhost:8080/api/shelves -d '{"name":"archive","locked":true}' # 201, copy the id
curl -i -X DELETE localhost:8080/api/shelves/THE_ID_ABOVE # 403 PERMISSION_DENIED, "library: shelf is locked"
curl -i -X DELETE localhost:8080/api/shelves/11111111-1111-1111-1111-111111111111 # 204
curl -i localhost:8080/api/shelves/11111111-1111-1111-1111-111111111111 # 404 NOT_FOUND, "library: not found"
Next: step 5 puts the data behind an interface so it can be swapped and faked (../05-storage-behind-an-interface).