Go Playbook

Course › Week 5 · HTTP services with net/http › Day 3 · lesson 31 of 42 · 15 min reading + 60 min practice

Shared dependencies and errors as responses

Handlers as methods on a struct that holds the pool, and one place that turns errors into status codes.

dependency injectionerror responsesstatus codes

On this page
  1. The service
  2. Coming from PHP
  3. Practice
  4. Remember

A real handler needs things: the database pool, a logger, an HTTP client, the config. Laravel’s service container injects them into controllers. Go has no container; the usual way is a server struct that holds them, built once in main, with the handlers as its methods.

The second half is errors. Writing a 404 or a 500 at every return repeats the same lines everywhere and gets them wrong somewhere. Instead, handlers return an error, and one function decides the response, the way bootstrap/app.php’s exception handling does.

The service

1. A server struct, built once

server has the pool and the logger. routes registers its methods as handlers: s.showBooking is a method value, a function bound to s, so when the mux calls it, it runs with s as its receiver and has s.db.

There is no global state: a test can build a server with a test database and a discarding logger, and call routes().

bookings/main.gochanged since lesson 11: +46 −7
package main import (	"bookings/pricing"	"fmt") 	"context"	"database/sql"	"log/slog"	"net/http"	"os"	"time" 	_ "github.com/jackc/pgx/v5/stdlib") // server holds what every handler needs. It is built once in main.type server struct {	db     *sql.DB	logger *slog.Logger} // routes is the routes/api.php of the service.func (s *server) routes() http.Handler {	mux := http.NewServeMux()	mux.HandleFunc("GET /api/bookings/{id}", s.handle(s.showBooking))	mux.HandleFunc("POST /api/bookings", s.handle(s.storeBooking))	return mux} func main() {	quote := pricing.Quote{nights: 0, nightlyCents: 12950} 	fmt.Println(quote.TotalCents())	logger := slog.New(slog.NewTextHandler(os.Stderr, nil)) 	db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))	if err != nil {		logger.Error("opening the database", "err", err)		os.Exit(1)	}	defer db.Close()	db.SetMaxOpenConns(10)	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)	defer cancel()	if err := db.PingContext(ctx); err != nil {		logger.Error("connecting to the database", "err", err)		os.Exit(1)	} 	s := &server{db: db, logger: logger}	logger.Info("listening", "addr", ":8080")	if err := http.ListenAndServe(":8080", s.routes()); err != nil {		logger.Error("server stopped", "err", err)		os.Exit(1)	}}

db.SetMaxOpenConns(10): a server handles requests concurrently, and each in-flight query holds a connection, so the pool size is the limit on concurrent database work. Set it below the Postgres connection limit shared with Laravel.

2. Handlers that return errors

Each handler has the signature of apiFunc: it writes the success response itself, and returns an error for everything else. errNotFound for a missing booking, a *validationError for bad input (the error-wrapping lesson), and any other error wrapped with what was being done.

r.Context() is the request’s context (the context lesson): it is cancelled when the client disconnects, so a query for a client who gave up stops too. Every database call in a handler takes it.

bookings/bookings.gonew file
package main

import (
	"database/sql"
	"encoding/json/v2"
	"errors"
	"fmt"
	"net/http"
	"strconv"
	"strings"
)

type Booking struct {
	ID         int64  `json:"id"`
	Guest      string `json:"guest"`
	Nights     int    `json:"nights"`
	TotalCents int64  `json:"total_cents"`
	Status     string `json:"status"`
}

type storeRequest struct {
	Guest  string `json:"guest"`
	Nights int    `json:"nights"`
}

const nightlyCents = 12950

func (s *server) showBooking(w http.ResponseWriter, r *http.Request) error {
	id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
	if err != nil {
		return errNotFound
	}
	var b Booking
	err = s.db.QueryRowContext(r.Context(), "select id, guest, nights, total_cents, status from bookings where id = $1", id).
		Scan(&b.ID, &b.Guest, &b.Nights, &b.TotalCents, &b.Status)
	if errors.Is(err, sql.ErrNoRows) {
		return errNotFound
	}
	if err != nil {
		return fmt.Errorf("reading booking %d: %w", id, err)
	}
	writeJSON(w, http.StatusOK, map[string]Booking{"data": b})
	return nil
}

func (s *server) storeBooking(w http.ResponseWriter, r *http.Request) error {
	var req storeRequest
	if err := json.UnmarshalRead(http.MaxBytesReader(w, r.Body, 64*1024), &req); err != nil {
		return &validationError{Message: "The request body is not valid JSON.", Errors: map[string][]string{}}
	}
	req.Guest = strings.TrimSpace(req.Guest)
	if req.Guest == "" || req.Nights < 1 || req.Nights > 28 {
		return &validationError{Message: "The given data was invalid.", Errors: map[string][]string{
			"booking": {"A booking needs a guest and 1 to 28 nights."},
		}}
	}

	b := Booking{Guest: req.Guest, Nights: req.Nights, TotalCents: int64(req.Nights) * nightlyCents, Status: "pending"}
	err := s.db.QueryRowContext(r.Context(),
		"insert into bookings (guest, nights, total_cents, created_at, updated_at) values ($1, $2, $3, now(), now()) returning id",
		b.Guest, b.Nights, b.TotalCents,
	).Scan(&b.ID)
	if err != nil {
		return fmt.Errorf("storing the booking: %w", err)
	}
	w.Header().Set("Location", fmt.Sprintf("/api/bookings/%d", b.ID))
	writeJSON(w, http.StatusCreated, map[string]Booking{"data": b})
	return nil
}

The validation is shorter than in the JSON lesson, to keep the focus here; the build day uses the full version.

3. One place for errors

handle adapts an apiFunc to an http.HandlerFunc, the type HandleFunc expects, by returning a closure (the closures lesson). The closure calls the handler and maps its error: validation to 422, not found to 404, everything else to 500.

A 500 logs the real error with the method and path, and tells the client only Server Error. That is Laravel with APP_DEBUG=false: a stack trace or an SQL message in a response is a gift to an attacker.

bookings/errors.gonew file
package main

import (
	"encoding/json/v2"
	"errors"
	"log/slog"
	"net/http"
)

// errNotFound means the thing the request names does not exist: 404.
var errNotFound = errors.New("not found")

// validationError is a request with wrong values: 422, with Laravel's shape.
type validationError struct {
	Message string              `json:"message"`
	Errors  map[string][]string `json:"errors"`
}

func (e *validationError) Error() string {
	return e.Message
}

// apiFunc is a handler that returns an error instead of writing it.
type apiFunc func(w http.ResponseWriter, r *http.Request) error

// handle turns an apiFunc into an http.HandlerFunc. It is the one place that decides which error
// becomes which response, like Laravel's exception handler.
func (s *server) handle(fn apiFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		err := fn(w, r)
		if err == nil {
			return
		}
		var invalid *validationError
		switch {
		case errors.As(err, &invalid):
			writeJSON(w, http.StatusUnprocessableEntity, invalid)
		case errors.Is(err, errNotFound):
			writeJSON(w, http.StatusNotFound, map[string]string{"message": "Not Found"})
		default:
			// The details go to the log, never to the client: they can contain SQL and table names.
			s.logger.Error("request failed", "method", r.Method, "path", r.URL.Path, "err", err)
			writeJSON(w, http.StatusInternalServerError, map[string]string{"message": "Server Error"})
		}
	}
}

// writeJSON sends v as a JSON response with the given status.
func writeJSON(w http.ResponseWriter, status int, v any) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	if err := json.MarshalWrite(w, v, json.Deterministic(true)); err != nil {
		slog.Error("writing the response", "err", err)
	}
}
$ curl -s -i http://127.0.0.1:8080/api/bookings/2
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 83

{"data":{"id":2,"guest":"Omar","nights":7,"total_cents":105070,"status":"pending"}}
$ curl -s -i http://127.0.0.1:8080/api/bookings/99
HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Length: 23

{"message":"Not Found"}
$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest": "Sara", "nights": 2}' http://127.0.0.1:8080/api/bookings
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/bookings/3
Content-Length: 82

{"data":{"id":3,"guest":"Sara","nights":2,"total_cents":25900,"status":"pending"}}
$ curl -s -i -X POST -H 'Content-Type: application/json' -d '{"guest": "", "nights": 40}' http://127.0.0.1:8080/api/bookings
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/json
Content-Length: 110

{"message":"The given data was invalid.","errors":{"booking":["A booking needs a guest and 1 to 28 nights."]}}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:04:28.796+02:00 level=INFO msg=listening addr=:8080

Four requests, four kinds of answer, and no handler wrote a single error response itself. The new booking got ID 3 and a Location header.

4. A 500, as the client and the log see it

The same service against a database where the bookings table is missing, as after a migration that failed half-way:

$ curl -s -i http://127.0.0.1:8080/api/bookings/1
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
Content-Length: 26

{"message":"Server Error"}
the server’s log (stderr), after Ctrl-C
time=2026-12-03T19:04:30.964+02:00 level=INFO msg=listening addr=:8080
time=2026-12-03T19:04:31.168+02:00 level=ERROR msg="request failed" method=GET path=/api/bookings/1 err="reading booking 1: ERROR: relation \"bookings\" does not exist (SQLSTATE 42P01)"

The client gets two words; the log gets the method, the path and the full chain: what the handler was doing and Postgres’s own message, relation "bookings" does not exist. That is enough to find the cause without ever exposing it.

Coming from PHP

bootstrap/app.php
<?php
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (BookingNotFound $e) {
        return response()->json(['message' => 'Not Found'], 404);
    });
})

// app/Http/Controllers/BookingController.php
public function __construct(private readonly BookingRepository $bookings) {}   // injected

The container builds controllers and injects what their constructors ask for; Go’s main builds the server by hand, in a few lines you can read. The exception handler maps exception classes to responses; handle maps error values and types. Both keep the controllers free of response-building for failures.

The difference: a PHP exception can come from anywhere below the controller and still be caught. A Go error arrives at handle only if every function on the way returned it, which is what the %w wrapping of the last weeks was for.

PracticeLearn Go with Tests: IO and sorting; one more error kind

Do IO and sorting in Learn Go with Tests: it moves its server’s store behind an interface, which is the next step after a server struct.

Exercise: a conflict

Add POST /api/bookings/{id}/confirm, which sets status to confirmed only when it is pending (update … where id = $1 and status = 'pending'). When no row changed, find out why: the booking does not exist (404), or it was not pending (409 Conflict with {"message": "Only a pending booking can be confirmed."}). Add an errConflict sentinel and its case in handle.

Remember

  • Dependencies live on a server struct built in main; handlers are its methods.
  • Handlers return errors, and one function maps them to statuses; a 500 logs the cause and tells the client nothing.
  • Every query in a handler takes r.Context().

Tomorrow: middleware, for what every request needs: logging, an API key check, timeouts and recovering from panics.