Documentation
¶
Overview ¶
Nested controllers and the two guard idioms: a group guard for every route and a positional guard for single routes.
ShelvesAPI mounts ItemsAPI with r.Router("/{shelf_id:uuid}/items", NewItemsAPI): a child router whose controller is resolved by the same container, so the nested API declares its own dependencies and owns its own route table.
Inside the child, guards are methods: they see the injected dependencies like any other handler. A group guard registered with r.Use runs before every route of the controller: requireShelf loads the shelf once, answers 404 when it does not exist and caches it on the request with ctx.Values().Set. A positional guard listed between path and handler protects individual routes: requireUnlocked runs on the writes only. Handlers read the cached shelf back with ctx.ValueAs, a typed lookup with no interface assertion at the call site.
A guard either calls ctx.Next() to continue or writes a response; the rest/errors senders stop the request for you.
Learn: mount a controller inside another one, guard all of its routes with r.Use and single routes with a positional handler, and cache a loaded value on the request for the handlers. Before: ../basic
Run:
go run main.go
Try:
OPEN=http://localhost:8080/api/shelves/11111111-1111-4111-8111-111111111111
LOCKED=http://localhost:8080/api/shelves/22222222-2222-4222-8222-222222222222
GONE=http://localhost:8080/api/shelves/33333333-3333-4333-8333-333333333333
curl http://localhost:8080/api/shelves # 200, both shelves
curl $OPEN/items # 200, one seeded item
curl -X POST $OPEN/items -d '{"title":"Go in Depth"}' # 201, {"id":"..."}
curl -i -X POST $LOCKED/items -d '{"t":1}' # 403, the positional guard
curl -i $GONE/items # 404, the group guard
Next: ../mvc-generics