06-controllers

command
v14.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: BSD-3-Clause Imports: 10 Imported by: 0

Documentation

Overview

Step 6 of 13: a controller instead of closures.

An Iris controller in this style is a plain struct with two things: a constructor, which is its dependency declaration, and a Routing(r iris.Router) method, which is its route table. The handlers are methods, so they all see the same injected service and the closures of step 5 disappear.

You never call the constructor yourself. app.RegisterDependency(svc) tells the application's container about the service, and app.Router("/api/shelves", NewShelvesAPI) hands the constructor to the container: it sees a parameter of type *Service, finds the registered value, calls NewShelvesAPI(svc) and then calls Routing once with the child router mounted at /api/shelves. Paths inside Routing are relative to the mount.

Learn: write a controller with a constructor and a Routing method, and let the container wire its dependencies. Before: ../05-storage-behind-an-interface

Run:

go run main.go

Try:

curl -i localhost:8080/api/shelves                                                  # 200
curl -i -X POST localhost:8080/api/shelves -d '{"name":"history"}'                  # 201
curl -i localhost:8080/api/shelves/11111111-1111-1111-1111-111111111111             # 200
curl -i -X DELETE localhost:8080/api/shelves/11111111-1111-1111-1111-111111111111   # 204

Next: step 7 nests books under shelves and guards the routes (../07-nested-routes-and-guards).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL