A controller for the couriers

Exercise 3 of 4 in chapter 1 · 100 XP · 2 objectives checked by tests

Topics covered: ControllerStructMethodSlice

routes/web.go is growing, and Margot already has more ideas. As in Laravel, the routes' code will move into a controller. Margot's nephew, who “does some Go”, started CoursierController and put the list of couriers in it.

Your mission

  1. In app/http/controllers/coursier_controller.go, add an Index method that responds {"coursiers": [...]} with the file's coursiers list.
  2. Add a Show method that does what the /couriers/{prenom} route does.
  3. In routes/web.go, create the controller with controllers.NewCoursierController(), wire GET /couriers to Index and GET /couriers/{prenom} to Show, and remove the old function.

Reminder

Go has no classes: a controller is a struct, empty here (type CoursierController struct{}), to which you attach methods. The (r *CoursierController) before the method name is its receiver, the equivalent of $this. The * and the & refer to the struct's address rather than a copy: just remember the shape for now, chapter 4 comes back to it. NewCoursierController() is a plain constructor, a Go convention rather than a keyword.

coursiers.Index, without parentheses, is the method itself, which the route will call on every request: it's Laravel's [CoursierController::class, 'index'].

[]string{"Margot", …} is a slice of strings, Go's list. Passed to Json, it becomes a JSON array.