Today's round

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

Topics covered: StructJSON tagQuery stringfor rangeappend

On to the deliveries. Margot's nephew wrote LivraisonController (livraison means “delivery”): a Livraison struct, today's round in memory, and a GET /deliveries route that sends all of it back. But a courier only rides in their own neighborhood, and the app would like to receive only their deliveries.

Your mission

  1. Read app/http/controllers/livraison_controller.go: the Livraison struct (Livree means “delivered”), its JSON tags, and the livraisons slice.
  2. In Index, read the quartier parameter (French for “neighborhood”) from the query string: GET /deliveries?quartier=croix-rousse.
  3. Without a neighborhood, nothing changes: the whole round. With a neighborhood, send back only its deliveries.
  4. A neighborhood without deliveries, like fourviere, responds with an empty list [].

Reminder

A struct groups named, typed fields, like a small class without methods. The text between backticks after each field is a tag: `json:"client"` tells the encoding/json package to write the Client field under the client key. Without a tag, the key would be Client. A field that starts with a capital letter is exported, visible outside its package; in lowercase, it would stay private and encoding/json would ignore it.

for _, livraison := range livraisons loops over a slice, like foreach ($livraisons as $livraison). An if is written without parentheses, and its braces are mandatory: if livraison.Quartier == quartier { … }. append adds an element and returns the grown slice: you always have to keep its result.

The classic trap: a slice that was never initialized is nil, and nil is written null in JSON. The app expects a list, even an empty one.