The depot key

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

Topics covered: MiddlewareHTTP headerInterface

The neighbor's son found the API's URL, and he's having fun ordering deliveries for his cat. Margot gave the couriers' app a key, which it sends in the X-Cle-Coursier header (“courier key”) of every request. The API has to check it.

Your mission

  1. In app/http/middleware/cle_coursier.go, complete Handle: without the X-Cle-Coursier header set to the right value (the cle constant), respond 401 with {"erreur": "missing courier key"}, and stop the request there.
  2. With the right key, let the request through to the controller.
  3. In routes/web.go, put the middleware on the /api group. /ping, /couriers and /board stay open.

The “Requests” tab sends one request with the key, and one without.

Reminder

A middleware runs before the controller, as in Laravel. For Goravel, it's a value with two methods, Handle(ctx http.Context) and Signature() string: it then satisfies the http.Middleware interface. In Go, you don't declare that a type implements an interface (there's no implements): having the right methods is enough.

In Handle, ctx.Request().Next() hands over to what comes next, Laravel's $next($request). AbortWithStatusJson responds right away; follow it with a return, so that Next() isn't called afterwards.

const cle = "gopher-volant" declares a constant, like const in PHP: its type is inferred, and it never changes.

The CleCoursier() constructor returns the middleware ready to use: that's what you pass to Middleware(…).