Documentation
¶
Overview ¶
Generic MVC controllers: five typed methods, the REST routes generated.
mvc.UseController[*T]() reads the method signatures of a type that satisfies mvc.Controller and registers the CRUD routes for it. Iris decodes the body into the Request type, converts the path id to the ID type, encodes the Response and installs the rest/errors handler on the child router. Your methods only return (value, error).
The generated path parameter is named after the Response model (Task becomes task_id) and its macro comes from the ID type: int, int64 and uint64 map to the matching macro, uuid.UUID maps to :uuid, and every other ID type, string included, stays :string. Declare the controller with uuid.UUID rather than string to have the router reject a malformed id before any handler runs. mvc.GetPathParam hands you that name inside the optional Routing method.
The controller itself comes from the container: it is resolved by type, or constructed and its exported fields bound from the registered dependencies, which is what happens to Store below.
Generated routes:
POST /tasks -> Create, 201
GET /tasks/{task_id:string} -> Get
PUT /tasks/{task_id:string}?columns -> Update, 200 (or 204/304 for a nil response)
DELETE /tasks/{task_id:string} -> Delete, 204/304
POST /tasks/list -> List, paginated
The generated handlers pick the decoder from the request's Content-Type, so a JSON body needs the header, unlike ctx.BindJSON, which always reads JSON.
Learn: have the CRUD routes of a resource generated from five typed controller methods with mvc.UseController, and add extra routes beside them. Before: ../nested-guards
Run:
go run main.go
Try:
H='Content-Type: application/json'
curl -H "$H" -X POST http://localhost:8080/tasks -d '{"title":"write docs"}' # 201, the task with its id
curl -H "$H" -X POST http://localhost:8080/tasks/list -d '{"done":false}' # 200, the Page envelope
curl http://localhost:8080/tasks/<the id from create> # 200, the task
curl -H "$H" -X PUT 'http://localhost:8080/tasks/<id>?columns=done' -d '{"done":true}' # 200, the updated task
curl -i -X DELETE http://localhost:8080/tasks/<id> # 204, then 304 on a second call
curl http://localhost:8080/tasks/param # 200, {"name":"task_id","type":"string"}
Next: ../repository