Go Playbook

Course › Week 6 · Laravel Go › Day 2 · lesson 37 of 42 · 35 min reading + 60 min practice

Routes, middleware and validation

Route files and groups, middleware, and validation on a typed struct.

routesmiddlewarevalidation

On this page
  1. Routes
  2. Input
  3. Middleware
  4. Coming from PHP
  5. Practice
  6. Remember

Week 5 wrote every piece of request handling by hand: matching routes (the routing lesson), decoding and checking JSON (the JSON lesson), and a middleware for an API key (the middleware lesson). Today Laravel Go does the same three jobs for the bookings API of Nordic Stays.

Each section shows what the framework decides for you, including one place where its choice is not the one an API wants.

Routes

1. A resource

route.Resource registers the conventional routes for the handlers you give it, like Route::apiResource. A field you leave out gets no route. The handlers are in handlers/bookings, shown in the next section.

routes/api.go
package routes

import (
	"go.laravel.com/config"
	"go.laravel.com/routing"

	"app/handlers/bookings"
)

func API(route *routing.Router, cfg *config.Config) {
	route.Resource("bookings", routing.Resource{
		Index: bookings.Index,
		Show:  bookings.Show,
	})
}
$ ./app route:list --path=api
Method    URI                      Name            Handler
GET|HEAD  /api/bookings            bookings.index  bookings.Index
GET|HEAD  /api/bookings/{booking}  bookings.show   bookings.Show
ANY       /api/{fallback...}                       go.laravel.com.notFound

Each route gets its conventional name, bookings.index and bookings.show, and the parameter is the singular of the resource’s name: {booking}. The starter’s /version route is gone because this API function no longer registers it.

2. A route parameter, and a 404 of your own

The handlers. The bookings are a fixed list for now; the models lesson moves them into Postgres.

handlers/bookings/bookings.go
package bookings

import (
	"net/http"
	"time"

	"go.laravel.com/date"
	"go.laravel.com/web"
)

type Booking struct {
	ID      int64     `json:"id"`
	Guest   string    `json:"guest"`
	Email   string    `json:"email"`
	CheckIn date.Date `json:"check_in"`
	Nights  int       `json:"nights"`
	Status  string    `json:"status"`
}

var all = []Booking{
	{ID: 5521, Guest: "Lina", Email: "lina@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 14}, Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Email: "omar@example.com", CheckIn: date.Date{Year: 2027, Month: time.February, Day: 2}, Nights: 7, Status: "pending"},
}

func Index(r *web.Request) *web.Response {
	return web.JSON(map[string][]Booking{"data": all})
}

func Show(r *web.Request) *web.Response {
	id, err := r.PathInt("booking")
	if err != nil {
		return web.Fail(err)
	}

	for _, b := range all {
		if b.ID == id {
			return web.JSON(map[string]Booking{"data": b})
		}
	}

	return web.Abortf(http.StatusNotFound, "No booking %d.", id)
}
$ curl -s -i http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 200 OK
Content-Length: 116
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: c27540ebd75a629936bbdabbda615d0e

{"data":{"id":5522,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending"}}
$ curl -s -i http://127.0.0.1:8080/api/bookings/9999
HTTP/1.1 404 Not Found
Content-Length: 30
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 1726fbe3943b4b726c5e1eaae4dfaa94

{"message":"No booking 9999."}
$ curl -s -i http://127.0.0.1:8080/api/bookings/abc
HTTP/1.1 404 Not Found
Content-Length: 23
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 3abe4ca3628b07552c97e90c18cc62ee

{"message":"Not Found"}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET     200  /api/bookings/5522  0.3ms
GET     404  /api/bookings/9999  0.2ms
GET     404  /api/bookings/abc  0.2ms
Stopping. Waiting up to 20s for the work in progress.

r.PathInt("booking") parses the parameter into an int64. When it is not a number, the error it returns is a 404, so web.Fail(err) answers like a route that does not exist: what strconv.ParseInt and a hand-written 404 did in the routing lesson.

web.Abortf(status, format, args…) answers with a status and a message, here a 404 that names the booking. In PHP it is abort(404, "No booking $id."). date.Date from go.laravel.com/date is a calendar day with no time or zone, written as 2027-02-02 in JSON.

Input

3. The query string, read into a struct

r.Query[Filters]() reads the query string into a struct by its json tags. A Rules method gives the fields their rules: validation.For lists them, and rule.Field(&f.Status, …) points at the field itself, so a misspelled field is a compile error instead of a rule that never runs.

handlers/bookings/bookings.go
package bookings

import (
	"net/http"
	"time"

	"go.laravel.com/date"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"
)

type Booking struct {
	ID      int64     `json:"id"`
	Guest   string    `json:"guest"`
	Email   string    `json:"email"`
	CheckIn date.Date `json:"check_in"`
	Nights  int       `json:"nights"`
	Status  string    `json:"status"`
}

var all = []Booking{
	{ID: 5521, Guest: "Lina", Email: "lina@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 14}, Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Email: "omar@example.com", CheckIn: date.Date{Year: 2027, Month: time.February, Day: 2}, Nights: 7, Status: "pending"},
}

type Filters struct {
	Status string `json:"status"`
}

func (f *Filters) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Status, rule.In("pending", "confirmed")),
	)
}

func Index(r *web.Request) *web.Response {
	filters, err := r.Query[Filters]()
	if err != nil {
		return web.Fail(err)
	}

	matching := []Booking{}
	for _, b := range all {
		if filters.Status == "" || b.Status == filters.Status {
			matching = append(matching, b)
		}
	}

	return web.JSON(map[string][]Booking{"data": matching})
}

func Show(r *web.Request) *web.Response {
	id, err := r.PathInt("booking")
	if err != nil {
		return web.Fail(err)
	}

	for _, b := range all {
		if b.ID == id {
			return web.JSON(map[string]Booking{"data": b})
		}
	}

	return web.Abortf(http.StatusNotFound, "No booking %d.", id)
}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=pending'
HTTP/1.1 200 OK
Content-Length: 118
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 615e13b6cdc265bf50bb8d5c5a46cd7f

{"data":[{"id":5522,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending"}]}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=deleted'
HTTP/1.1 200 OK
Content-Length: 228
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 654eb3ebcf8ec69688e8e9aa9d4f6c5d

{"data":[{"id":5521,"guest":"Lina","email":"lina@example.com","check_in":"2027-01-14","nights":3,"status":"confirmed"},{"id":5522,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending"}]}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET     200  /api/bookings  0.4ms
GET     200  /api/bookings  0.4ms
Stopping. Waiting up to 20s for the work in progress.

?status=pending filters. ?status=deleted does not fail: it returns every booking. That is the framework’s documented choice for query strings: for an optional field, r.Query drops a value that breaks a rule and keeps the zero value, so a stale bookmark still opens the page.

For a page that is kind. For an API it is a silent failure: a client with a typo in a filter gets the wrong rows and a 200, and never finds out.

4. A strict query string

Without a Rules method, r.Query only reads the values. validation.Validate(r, &filters, rules…) then checks them, and web.InvalidErrors answers the failures the way failed validation always is answered:

handlers/bookings/bookings.go
package bookings

import (
	"net/http"
	"time"

	"go.laravel.com/date"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"
)

type Booking struct {
	ID      int64     `json:"id"`
	Guest   string    `json:"guest"`
	Email   string    `json:"email"`
	CheckIn date.Date `json:"check_in"`
	Nights  int       `json:"nights"`
	Status  string    `json:"status"`
}

var all = []Booking{
	{ID: 5521, Guest: "Lina", Email: "lina@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 14}, Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Email: "omar@example.com", CheckIn: date.Date{Year: 2027, Month: time.February, Day: 2}, Nights: 7, Status: "pending"},
}

type Filters struct {
	Status string `json:"status"`
}

func Index(r *web.Request) *web.Response {
	filters, err := r.Query[Filters]()
	if err != nil {
		return web.Fail(err)
	}

	failed, err := validation.Validate(r, &filters,
		rule.Field(&filters.Status, rule.In("pending", "confirmed")),
	)
	if err != nil {
		return web.Fail(err)
	}
	if len(failed) > 0 {
		return web.InvalidErrors(failed)
	}

	matching := []Booking{}
	for _, b := range all {
		if filters.Status == "" || b.Status == filters.Status {
			matching = append(matching, b)
		}
	}

	return web.JSON(map[string][]Booking{"data": matching})
}

func Show(r *web.Request) *web.Response {
	id, err := r.PathInt("booking")
	if err != nil {
		return web.Fail(err)
	}

	for _, b := range all {
		if b.ID == id {
			return web.JSON(map[string]Booking{"data": b})
		}
	}

	return web.Abortf(http.StatusNotFound, "No booking %d.", id)
}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=deleted'
HTTP/1.1 422 Unprocessable Entity
Content-Length: 101
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 10ff73c3bbf746680faf488fd3719956

{"errors":{"status":["The selected status is invalid."]},"message":"The selected status is invalid."}
$ curl -s -i 'http://127.0.0.1:8080/api/bookings?status=pending'
HTTP/1.1 200 OK
Content-Length: 118
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 60ccff9bb216803bdaec577b5044b12b

{"data":[{"id":5522,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending"}]}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET     422  /api/bookings  0.4ms
GET     200  /api/bookings  0.3ms
Stopping. Waiting up to 20s for the work in progress.

Now a status that is not one of the two is a 422 in Laravel’s shape, and a missing one still lists everything, because In skips a field that is empty. Validate returns two things: failed, the fields that broke a rule, and err, which means a rule could not run at all (a database rule whose query failed), a server error.

5. A JSON body, validated: the Form Request

r.Validate[StoreBooking]() fills the struct from the body and runs its rules. The struct and its Rules method are a Form Request’s rules(), typed:

handlers/bookings/bookings.go
package bookings

import (
	"net/http"
	"time"

	"go.laravel.com/date"
	"go.laravel.com/validation"
	"go.laravel.com/validation/rule"
	"go.laravel.com/web"
)

type Booking struct {
	ID      int64     `json:"id"`
	Guest   string    `json:"guest"`
	Email   string    `json:"email"`
	CheckIn date.Date `json:"check_in"`
	Nights  int       `json:"nights"`
	Status  string    `json:"status"`
}

var all = []Booking{
	{ID: 5521, Guest: "Lina", Email: "lina@example.com", CheckIn: date.Date{Year: 2027, Month: time.January, Day: 14}, Nights: 3, Status: "confirmed"},
	{ID: 5522, Guest: "Omar", Email: "omar@example.com", CheckIn: date.Date{Year: 2027, Month: time.February, Day: 2}, Nights: 7, Status: "pending"},
}

type Filters struct {
	Status string `json:"status"`
}

func Index(r *web.Request) *web.Response {
	filters, err := r.Query[Filters]()
	if err != nil {
		return web.Fail(err)
	}

	failed, err := validation.Validate(r, &filters,
		rule.Field(&filters.Status, rule.In("pending", "confirmed")),
	)
	if err != nil {
		return web.Fail(err)
	}
	if len(failed) > 0 {
		return web.InvalidErrors(failed)
	}

	matching := []Booking{}
	for _, b := range all {
		if filters.Status == "" || b.Status == filters.Status {
			matching = append(matching, b)
		}
	}

	return web.JSON(map[string][]Booking{"data": matching})
}

func Show(r *web.Request) *web.Response {
	id, err := r.PathInt("booking")
	if err != nil {
		return web.Fail(err)
	}

	for _, b := range all {
		if b.ID == id {
			return web.JSON(map[string]Booking{"data": b})
		}
	}

	return web.Abortf(http.StatusNotFound, "No booking %d.", id)
}

type StoreBooking struct {
	Guest   string    `json:"guest"`
	Email   string    `json:"email" transform:"lowercase"`
	CheckIn date.Date `json:"check_in"`
	Nights  int       `json:"nights"`
}

func (f *StoreBooking) Rules() validation.Rules {
	return validation.For(f,
		rule.Field(&f.Guest, rule.Required, rule.Max(100)),
		rule.Field(&f.Email, rule.Required, rule.Email),
		rule.Field(&f.CheckIn, rule.Required),
		rule.Field(&f.Nights, rule.Required, rule.Min(1), rule.Max(30)),
	)
}

func Store(r *web.Request) *web.Response {
	form, err := r.Validate[StoreBooking]()
	if err != nil {
		return web.Fail(err)
	}

	booking := Booking{
		Guest:   form.Guest,
		Email:   form.Email,
		CheckIn: form.CheckIn,
		Nights:  form.Nights,
		Status:  "pending",
	}

	return web.Created(map[string]Booking{"data": booking})
}
$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest":"Sara","email":"Sara@Example.COM","check_in":"2027-03-01","nights":2}' http://127.0.0.1:8080/api/bookings
HTTP/1.1 201 Created
Content-Length: 113
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 6abd18b120b23ebb96d4c37539133803

{"data":{"id":0,"guest":"Sara","email":"sara@example.com","check_in":"2027-03-01","nights":2,"status":"pending"}}
$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest":"","email":"nope","check_in":"2027-02-30","nights":"two"}' http://127.0.0.1:8080/api/bookings
HTTP/1.1 422 Unprocessable Entity
Content-Length: 279
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: ea9438d667773eb313dd09651fc355d2

{"message":"The guest field is required. (and 3 more errors)","errors":{"guest":["The guest field is required."],"email":["The email field must be a valid email address."],"check_in":["The check in field must be a valid date."],"nights":["The nights field must be an integer."]}}
$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest":"Sara",' http://127.0.0.1:8080/api/bookings
HTTP/1.1 400 Bad Request
Content-Length: 49
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 8fc42454f9d44e785513d185b6f4f0e0

{"message":"The request body is not valid JSON."}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST    201  /api/bookings  0.5ms
POST    422  /api/bookings  0.6ms
POST    400  /api/bookings  0.1ms
Stopping. Waiting up to 20s for the work in progress.

The good booking is a 201 from web.Created. Its email arrived as Sara@Example.COM and was stored lowercase: the transform:"lowercase" tag runs while the body is read, before the rules. id is 0 because nothing has saved it yet.

The bad one is a 422 with every field’s message, the exact JSON a Laravel 422 has. The types are rules too: "two" is not an int, and 2027-02-30 is not a date.Date. A body that is not JSON at all is a 400 before your handler runs. That is the whole of the JSON lesson, with the limits and the error shapes chosen for you.

6. Only the fields the struct names

The same handler, with a client that sends fields it should not:

$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest":"Sara","email":"sara@example.com","check_in":"2027-03-01","nights":2,"id":1,"status":"confirmed"}' http://127.0.0.1:8080/api/bookings
HTTP/1.1 201 Created
Content-Length: 113
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 2a3679c818fb832b0c8c6eed99167c68

{"data":{"id":0,"guest":"Sara","email":"sara@example.com","check_in":"2027-03-01","nights":2,"status":"pending"}}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
POST    201  /api/bookings  0.7ms
Stopping. Waiting up to 20s for the work in progress.

id and status are not in StoreBooking, so they never reach the handler, and Store sets Status itself. Copying each field from the form into the Booking by hand is the point: the struct literal is the list of what a client may set, Laravel’s $fillable checked by the compiler. Do not validate into the model’s own struct, or a client may set every field of it.

Unknown fields are ignored without a word, as in PHP Laravel, where $request->validated() drops them. The JSON lesson rejected them with RejectUnknownMembers; here, that strictness is gone.

Middleware

7. A middleware with a key from .env

A middleware is a type with a Handle(r, next) method: call next(r) to go on, or return a response to stop. The key comes from the environment, read once in services.New:

services/services.go
package services

import (
	"context"

	laravel "go.laravel.com"
	"go.laravel.com/config"
)

type Services struct {
	// APIKey is the key that callers of the bookings API send as a Bearer token.
	APIKey string
}

func New(env *config.Env, app *laravel.App) Services {
	return Services{
		APIKey: env.String("NORDIC_API_KEY", ""),
	}
}

func From(ctx context.Context) *Services {
	return laravel.ServicesOf[*Services](ctx)
}

env.String(name, fallback) reads .env, or the process’s environment on a server. The fallback is empty on purpose: services.New runs for every command, key:generate included, so it must not fail on a fresh clone. The code that uses the key reports it missing instead.

8. The middleware, and a group

The middleware lives in a package named for what it does, and the routes that need it are registered through a group:

apikeys/apikeys.go
package apikeys

import (
	"crypto/subtle"
	"errors"
	"net/http"
	"strings"

	"go.laravel.com/web"

	"app/services"
)

// Required lets a request through only with the API key as its Bearer token.
type Required struct{}

func (Required) Handle(r *web.Request, next web.Next) *web.Response {
	key := services.From(r).APIKey
	if key == "" {
		return web.Fail(errors.New("apikeys: NORDIC_API_KEY is not set"))
	}

	sent, ok := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
	if !ok || subtle.ConstantTimeCompare([]byte(sent), []byte(key)) != 1 {
		return web.Abort(http.StatusUnauthorized)
	}

	return next(r)
}
$ ./app route:list --path=api --middleware
Method    URI                      Name            Handler
GET|HEAD  /api/bookings            bookings.index  bookings.Index
                                                   ⇂ apikeys.Required
POST      /api/bookings            bookings.store  bookings.Store
                                                   ⇂ apikeys.Required
GET|HEAD  /api/bookings/{booking}  bookings.show   bookings.Show
                                                   ⇂ apikeys.Required
ANY       /api/{fallback...}                       go.laravel.com.notFound
$ curl -s -i http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 500 Internal Server Error
Content-Length: 78
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: e510ec6e78d8fd401f6fefd44e1fe3bc

{"message":"apikeys: NORDIC_API_KEY is not set","error":"*errors.errorString"}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
time=2026-12-03T21:16:00.023+02:00 level=ERROR msg="apikeys: NORDIC_API_KEY is not set" method=GET path=/api/bookings/5522 location=/tmp/go-playbook/app/apikeys/apikeys.go:20 type=*errors.errorString request_id=e510ec6e78d8fd401f6fefd44e1fe3bc
GET     500  /api/bookings/5522  1.3ms
Stopping. Waiting up to 20s for the work in progress.

route.Middleware(apikeys.Required{}) returns a router whose routes all run it; route:list --middleware shows it under each one. m.API.Append(apikeys.Required{}) in bootstrap/app.go would put it on every API route instead.

Here NORDIC_API_KEY is not set, so every request is a 500 whose message names the missing variable, and the log line has the file and line, the path and the request id. The response shows the message only because APP_DEBUG=true in .env.

9. With the key, and in production

The same app with NORDIC_API_KEY in its environment: no key, a wrong key, the right key.

$ curl -s -i http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 401 Unauthorized
Content-Length: 26
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: ca10c792ae64e9ee508481075a447682

{"message":"Unauthorized"}
$ curl -s -i -H 'Authorization: Bearer wrong' http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 401 Unauthorized
Content-Length: 26
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 6fa8ecbad644eb2ddc4a3e345905e2dd

{"message":"Unauthorized"}
$ curl -s -i -H 'Authorization: Bearer nordic-local-key' http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 200 OK
Content-Length: 116
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 92030fb190745b9c41bd3fa75a7cd60c

{"data":{"id":5522,"guest":"Omar","email":"omar@example.com","check_in":"2027-02-02","nights":7,"status":"pending"}}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
GET     401  /api/bookings/5522  0.2ms
GET     401  /api/bookings/5522  0.1ms
GET     200  /api/bookings/5522  0.3ms
Stopping. Waiting up to 20s for the work in progress.

The comparison is subtle.ConstantTimeCompare, as in the middleware lesson, so the time a wrong key takes does not tell an attacker how much of it was right. The 401’s body is the framework’s.

10. APP_DEBUG=false

The missing key again, with APP_DEBUG=false, as on a production server:

$ curl -s -i http://127.0.0.1:8080/api/bookings/5522
HTTP/1.1 500 Internal Server Error
Content-Length: 26
Content-Type: application/json
Vary: Origin
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
X-Request-Id: 37d3f0fc420562eb249d16d58714e555

{"message":"Server Error"}
the log of ./app (the server), after Ctrl-C
Server running at `http://127.0.0.1:8080`. Press Ctrl+C to stop.
time=2026-12-03T21:16:06.992+02:00 level=ERROR msg="apikeys: NORDIC_API_KEY is not set" method=GET path=/api/bookings/5522 location=/tmp/go-playbook/app/apikeys/apikeys.go:20 type=*errors.errorString request_id=37d3f0fc420562eb249d16d58714e555
GET     500  /api/bookings/5522  0.3ms
Stopping. Waiting up to 20s for the work in progress.

The client gets Server Error and nothing else; the cause stays in the log. This is the rule the dependencies lesson wrote by hand: a 500 logs the cause and tells the client nothing. Check APP_DEBUG=false before every deploy.

Coming from PHP

app/Http/Requests/StoreBookingRequest.php
<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class StoreBookingRequest extends FormRequest
{
    public function rules(): array
    {
        return [
            'guest' => ['required', 'string', 'max:100'],
            'email' => ['required', 'email'],
            'check_in' => ['required', 'date'],
            'nights' => ['required', 'integer', 'min:1', 'max:30'],
        ];
    }
}

The rules are the same words: required, max:100, email. The differences are in where they point. PHP names fields in strings, so 'nigths' is a rule that never runs; Go points at &f.Nights, and a typo does not compile. PHP needs integer and date rules; in Go the field’s type is the rule. And $request->validated() is an array, while r.Validate gives you a typed StoreBooking, so the handler cannot read a field that was never validated.

Middleware reads the same: handle($request, Closure $next) becomes Handle(r, next). One difference: Laravel resolves middleware from the container by class name, and Laravel Go takes a value, apikeys.Required{}, which the compiler checks.

PracticeThe validation guide; PATCH with fields a request may leave out

Read validation.md in the app’s bundled docs (the Laravel Go lesson shows how to find them): the quickstart, the available rules, and “Fields a request may leave out”.

Exercise: change the nights

Add Update to the resource, for PATCH /api/bookings/{booking}. Its input is type UpdateBooking struct { Nights validation.Sometimes[int] json:"nights" } with rule.Required, rule.Min(1), rule.Max(30). Answer 200 with the booking and its new nights, without changing all (it is shared by every request goroutine). Check that {} keeps the nights, {"nights": 0} is a 422, and {"nights": null} is a 422 too.

Remember

  • Input goes into a struct with r.Validate or r.Query; copy each allowed field into the model by hand.
  • r.Query drops a value that breaks a rule: for an API, check filters with validation.Validate and answer web.InvalidErrors.
  • Read secrets in services.New with an empty fallback, and fail where they are used, with the variable’s name.
  • Ship with APP_DEBUG=false.

Tomorrow: models and migrations, and the bookings move into Postgres.