Running Go natively in the cloud: multi-stage Dockerfiles with distroless images, 12-factor configuration with clean liveness and readiness endpoints, Kubernetes automation with client-go, operators built on controller-runtime and kubebuilder, and sidecars, webhooks & CRDs as extension patterns.
The "Kant & Curves" bookshop wants to put its inventory online. The plan covers roughly thirty routes, a public area under /api/v1, an admin section, and eventually an OpenAPI description. The team's first architecture question: which framework do we pick? The honest Go answer starts with a dampener: net/http has handled method patterns and wildcards without any extra package since Go 1.22 (lesson 46) — pure route resolution needs no framework. What frameworks sell is ergonomics: route groups, built-in middleware, JSON binding to structs, generated help text, and an ecosystem of ready-made parts.
The candidates, with their exact import paths: chi (github.com/go-chi/chi/v5) stays 100% compatible with net/http — handlers, middleware, and http.Server remain untouched. Gin (github.com/gin-gonic/gin) brings the largest ecosystem and its own handler signature (*gin.Context). Echo (github.com/labstack/echo/v4) sits in the middle: its own slim handler contract with an error return value, but net/http underneath. Fiber (github.com/gofiber/fiber/v2) promises Express ergonomics and throughput — but builds on fasthttp, not net/http, which swaps the foundations under your feet.
Whatever the decision: the REST conventions — resources as nouns, clean status codes, versioning through the path — do not come from the router, they come from API design. The architecture course covers them in Module 5: API Design; Gin and Echo merely implement those rules later. Teams that "invent" them at the router pay with inconsistencies their clients feel expensively.
The Router Is Replaceable — the Domain Is Not
All four candidates solve the same problem: mapping a path plus a method onto a function. Your handler cores — catalog, cart, pricing — never know the router. Keep handlers thin for exactly that reason: parse, call the domain, respond. Then the router is a decision for a quarter, not for eternity, and switching it only touches the edge layer.
The same endpoint twice — chi first, entirely in net/http style:
// internal/router/router.go — chi: groups and middleware, still plain net/http
package router
import (
"net/http"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
)
func New(list ListBooks, byISBN BookByISBN) http.Handler {
r := chi.NewRouter()
r.Use(middleware.RequestID) // generate X-Request-Id if the client sends none
r.Use(middleware.Recoverer) // panics become clean 500s
r.Use(middleware.Logger) // access log without any custom work
r.Route("/api/v1", func(api chi.Router) {
api.Get("/books", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, list(r.Context()))
})
api.Get("/books/{isbn}", func(w http.ResponseWriter, r *http.Request) {
b, err := byISBN(r.Context(), chi.URLParam(r, "isbn"))
if err != nil {
http.NotFound(w, r)
return
}
writeJSON(w, http.StatusOK, b)
})
})
return r
}
// Terminal: curl -s localhost:8080/api/v1/books/978-0-06-231500-7
// → {"isbn":"978-0-06-231500-7","title":"The Alchemist","author":"Paulo Coelho","price_cents":1099,"stock":3}
Now Gin — the same two routes, shorter handlers, its own context object:
// cmd/server/main.go — Gin: groups, binding, and a middleware chain out of the box
package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default() // = gin.New() + Logger + Recovery, pre-wired
v1 := r.Group("/api/v1")
{
v1.GET("/books/:isbn", func(c *gin.Context) {
b, err := fetchBook(c.Request.Context(), c.Param("isbn"))
if err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "book not found"})
return
}
c.JSON(http.StatusOK, b)
})
}
log.Fatal(r.Run(":8080"))
}
// Terminal: curl -s localhost:8080/api/v1/books/978-0-06-231500-7
// → {"isbn":"978-0-06-231500-7","title":"The Alchemist","author":"Paulo Coelho","price_cents":1099,"stock":3}
Echo and Fiber side by side — same path, different handler contracts:
// Comparison: the same endpoint in Echo and Fiber
func echoRoutes(e *echo.Echo) {
e.GET("/api/v1/books/:isbn", func(c echo.Context) error {
return c.JSON(http.StatusOK, fetchBook(c.Request.Context(), c.Param("isbn")))
})
}
func fiberRoutes(app *fiber.App) {
app.Get("/api/v1/books/:isbn", func(c *fiber.Ctx) error {
return c.Status(http.StatusOK).JSON(fetchBook(c.Request.Context(), c.Params("isbn")))
})
}
// Terminal: curl -s localhost:8080/api/v1/books/978-0-06-231500-7
// → {"isbn":"978-0-06-231500-7", ...} — Echo and Fiber, identical path, identical answer
The real difference is not syntax but the foundation:
| Router | Package | Foundation | Middleware type |
|---|---|---|---|
net/http | standard library | net/http | func(http.Handler) http.Handler |
| chi | github.com/go-chi/chi/v5 | net/http | identical to the standard library |
| Gin | github.com/gin-gonic/gin | own routing tree | func(*gin.Context) |
| Echo | github.com/labstack/echo/v4 | own handler contract | echo.MiddlewareFunc |
| Fiber | github.com/gofiber/fiber/v2 | fasthttp | func(*fiber.Ctx) error |
For the bookshop the decision lands like this: the team knows net/http inside out from module 10 — chi would be the lowest-risk addition. But the Gin ecosystem (binding, validation, ready middleware) saves real time across thirty routes. The pick is Gin for the API layer; the domain stays router-free. That separation pays off in lesson 60.
⚠ Common mistake: Porting routes 1:1 from
net/httpto Gin and tripping over the startup panic. TheServeMuxresolvesGET /books/newnext toGET /books/{isbn}silently — the literal segment wins (lesson 46). Gin's httprouter tree allows only one wildcard pattern at the same position and dies during registration with a conflict likeconflicts with existing wildcard. Every router has its own precedence rules: after any router switch, run the full route table through a test pass before anything reaches production.
Check: The team wants method patterns like GET /books/{isbn}. Which statement is true?
Answer: net/http has done it natively since Go 1.22; frameworks mostly buy ergonomics, groups, and ecosystem
The most common misconception treats method patterns as a framework feature. In reality the ServeMux has handled methods, wildcards, and precedence since Go 1.22 (lesson 46). Frameworks still earn their keep: chi adds groups and built-in middleware at full net/http compatibility; Gin, Echo, and Fiber add binding, validation ecosystems, and generated help.
Takeaways:
net/http has handled method and wildcard patterns since Go 1.22 — a framework is an ergonomics decision, not a requirement.github.com/go-chi/chi/v5) stays fully net/http-compatible; Gin, Echo, and Fiber bring their own handler contracts.fasthttp, not net/http — middleware, timeouts, and streaming behave differently from what you expect.The shop grows, and so do the requirements: POST /api/v1/admin/books may only be called by staff with a valid token, every response must be findable in the log by request ID, and a panicking handler must never tear the connection apart. In module 10 (lesson 48) you built that onion by hand — func(http.Handler) http.Handler, recovery outside, logging inside. Now we industrialize it: frameworks ship the chain ready-made, but the engineering questions stay the same. In which order? How do values like the logged-in user reach the handler? And what happens on an abort in the middle?
The core idea for values: request-scoped data travels in the context, never in global variables. Gin parks it with c.Set/c.MustGet on the gin.Context; chi and net/http use context.WithValue with a private key type — race-free by construction and automatically gone when the request ends.
Chain Order Is a Security Decision
Stacked, the onion from lesson 48 still applies: recovery outermost (it catches panics from EVERYTHING below it), then request ID and logging, only then auth, then the handler. Put auth outside and logging inside, and rejected requests never reach the log — you will wonder about 401s that officially never happened. Logging BEFORE auth, on the other hand, means attack attempts land in the log in structured form.
The auth middleware in Gin — parse the bearer token, look up the user, park it in the context:
// internal/api/middleware.go
package api
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// RequireUser checks the bearer token and stores the user in the request context.
func RequireUser(users UserLookup) gin.HandlerFunc {
return func(c *gin.Context) {
token, ok := strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ")
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized,
gin.H{"error": "bearer token required"})
return // mandatory! Abort stops the chain, NOT this function
}
u, err := users.ByToken(c.Request.Context(), token)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized,
gin.H{"error": "token invalid or expired"})
return
}
c.Set("user", u)
c.Next()
}
}
// Wiring: the admin group guards everything beneath it in one sweep
admin := r.Group("/api/v1/admin")
admin.Use(RequireUser(users))
{
admin.POST("/books", addBook)
}
func addBook(c *gin.Context) {
u := c.MustGet("user").(User) // from the middleware, type-asserted
c.JSON(http.StatusCreated, gin.H{"created_by": u.Name})
}
// Terminal: curl -s -X POST localhost:8080/api/v1/admin/books
// → {"error":"bearer token required"} (HTTP 401)
//
// Terminal: curl -s -X POST localhost:8080/api/v1/admin/books -H "Authorization: Bearer $TOKEN"
// → {"created_by":"Lena"} (HTTP 201)
For the chi/net/http world, the same pattern with structured logging — log/slog has been in the standard library since Go 1.21:
// internal/api/slogmw.go — request ID and structured logging with slog
package api
import (
"context"
"fmt"
"log/slog"
"net/http"
"time"
)
type ctxKey int
const requestIDKey ctxKey = 1
func WithRequestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := r.Header.Get("X-Request-Id")
if id == "" {
id = fmt.Sprintf("req-%d", time.Now().UnixNano())
}
w.Header().Set("X-Request-Id", id)
next.ServeHTTP(w, r.WithContext(
context.WithValue(r.Context(), requestIDKey, id)))
})
}
func WithSlog(logger *slog.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK} // from lesson 48
next.ServeHTTP(rec, r)
logger.Info("request",
"request_id", r.Context().Value(requestIDKey),
"method", r.Method,
"path", r.URL.Path,
"status", rec.status,
"dur_ms", time.Since(start).Milliseconds(),
)
})
}
}
// Terminal: curl -s localhost:8080/api/v1/books
// → {"time":"2026-11-05T21:40:12+01:00","level":"INFO","msg":"request",
// → "request_id":"req-1790943612345678901","method":"GET","path":"/api/v1/books","status":200,"dur_ms":3}
The log is now machine-queryable — every field addressable instead of fished out of a text line with regexes. Later in production you will hang OpenTelemetry spans (go.opentelemetry.io/otel) at exactly this spot; module 13 shows how. The chain just grows another link; the onion logic stays.
⚠ Common mistake: Calling
c.AbortWithStatusJSON(401, ...)and then happily continuing — withoutreturn. Abort only sets a flag that halts the REST of the chain; your own function body keeps running. The typical fallout: code after the abort writes again or redirects, the response contains garbage, or Gin logssuperfluous response.WriteHeader. Every abort needs areturnright after it — the middleware above does so explicitly.
Check: RequireUser calls c.AbortWithStatusJSON(401, ...) — and NO return. What happens to the code directly after the abort call, in the same middleware?
Answer: It runs on — Abort only stops the remaining handler chain; your own function must return on its own
The misconception comes from languages with exceptions, where throw acts like a control-flow jump. Abort is just a flag on the gin.Context — remaining handlers get skipped, but the code after it in your function is guaranteed to run. That is why real codebases put a return after every abort, often with a comment securing exactly that.
Takeaways:
c.Set/c.MustGet in Gin, context.WithValue with a private key type in chi and net/http.log/slog (since Go 1.21) makes middleware logging structurally queryable — request ID, status, and duration as their own fields.AbortWithStatus/AbortWithStatusJSON needs a return right after it: Abort stops the chain, not your own function.So far the books live in memory; the first restart would wipe them. The move to PostgreSQL is due, and the team is having the classic fundamental debate: an ORM for development speed, or SQL for operational speed? This is not a Go quirk but a data architecture decision — Module 6: Data Architecture treats ORM vs. code generation as a pattern with long-lived consequences. Here are the four Go candidates, honestly sorted:
github.com/jackc/pgx/v5 is the PostgreSQL driver with a connection pool (pgxpool) — very fast, full SQL, but every query by hand. github.com/jmoiron/sqlx sits as a thin layer over database/sql and scans rows straight into structs (StructScan) — convenient, but the column cast happens at runtime. GORM (gorm.io/gorm with gorm.io/driver/postgres) is the full ORM: associations, hooks, AutoMigrate — and an abstraction that leaks on complex joins and bulk operations. sqlc (github.com/sqlc-dev/sqlc, installed as a CLI) flips the approach: you write the SQL, sqlc generates type-safe Go code from it — the failure point moves from runtime to code generation.
sqlc: SQL Is the Contract — the Compiler Checks It
With sqlc, the SQL lives in a query file annotated with -- name: GetBookByISBN :one. sqlc generate produces a Go function with a matching signature and a struct per column tuple. A typo in a column name, a wrong parameter type — both surface during generation, not at 3 a.m. in production. You still write real SQL; what you gain is type safety over what the database can actually do.
The sqlc path — the query file first (hand-written), then the generated caller:
-- db/query/books.sql — SQL first, annotations drive the generation
-- name: GetBookByISBN :one
SELECT isbn, title, author, price_cents, stock FROM books WHERE isbn = $1;
-- name: ListBooks :many
SELECT isbn, title, author, price_cents, stock FROM books ORDER BY title LIMIT $1;
-- name: DecrementStock :exec
UPDATE books SET stock = stock - 1 WHERE isbn = $1 AND stock > 0;
// db/sqlc/books.sql.go — generated by `sqlc generate`, never hand-written
func (q *Queries) GetBookByISBN(ctx context.Context, isbn string) (Book, error) {
row := q.db.QueryRow(ctx,
`SELECT isbn, title, author, price_cents, stock FROM books WHERE isbn = $1`, isbn)
var i Book
err := row.Scan(&i.Isbn, &i.Title, &i.Author, &i.PriceCents, &i.Stock)
return i, err
}
// internal/catalog/service.go — calling it: type-safe, no interface conversions
b, err := q.GetBookByISBN(ctx, "978-0-06-231500-7")
if errors.Is(err, pgx.ErrNoRows) {
return ErrNotFound // the mapping onto HTTP status codes follows in lesson 60
}
// Terminal: go build ./...
// → (compiles — SQL and Go types match, guaranteed by the generator)
For comparison, GORM — less SQL, more negotiation with the abstraction:
// internal/catalog/gorm_repo.go — the same result with GORM
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
if err := db.AutoMigrate(&Book{}); err != nil { // schema from the struct
log.Fatal(err)
}
var b Book
err = db.Where("isbn = ?", "978-0-06-231500-7").First(&b).Error
// First returns gorm.ErrRecordNotFound on an empty result —
// Find returns an empty slice with a nil error instead. Never mix them!
// Terminal: go test ./internal/catalog/
// → ok bookstore/internal/catalog 0.412s
And sqlx as the thinnest middle ground — structs without a generator, checked only at runtime:
// sqlx: database/sql with StructScan — pragmatic, but untyped until runtime
rows, err := dbx.QueryxContext(ctx,
`SELECT isbn, title, price_cents FROM books WHERE stock > $1 ORDER BY title`, 0)
if err != nil {
return nil, err
}
defer rows.Close()
var found []Book
for rows.Next() {
var b Book
if err := rows.StructScan(&b); err != nil {
return nil, err
}
found = append(found, b)
}
// → scanned 2 in-stock books — a column typo here would surface only at runtime
| Tool | Approach | Strength | Cost |
|---|---|---|---|
pgx/v5 | driver + pool | speed, full SQL control | every query by hand |
sqlx | reflection over database/sql | StructScan, NamedExec | no compile-time checks |
sqlc | code generation from SQL | type-safe at generation time | think SQL first, keep a CLI in the build |
| GORM | ORM | associations, AutoMigrate, hooks | the abstraction leaks on complex joins |
For the bookshop: the team knows SQL, the queries are mostly straightforward, and inventory is critical (double-selling a book costs more than a minute of extra implementation). The pick is sqlc on pgx — GORM would be the answer if rapid prototyping and many CRUD tables dominated. Lesson 60 cashes in that decision when the API gets built for real.
⚠ Common mistake: Guarding
db.Find(&books, ...)witherrors.Is(err, gorm.ErrRecordNotFound)and wondering why the error branch never fires.Findreturns NO error on an empty result, just an empty slice —ErrRecordNotFoundexists only forFirst/Take/Last. To detect "not found" withFindyou must checklen(books) == 0; the error check suggests a safety that never happens.
Check: In the sqlc path, the query contains a typo in a column name (autor instead of author). When does the mistake surface?
Answer: Immediately at
sqlc generateor the next build — the generator validates the SQL against the schemaThat is the whole point of sqlc: the generator knows the schema (from your migrations) and checks every query against it. The typo breaks
sqlc generate— the build stays red until the SQL is right. In the GORM path, the same mistake typically surfaces at runtime when the first scan fails.
Takeaways:
pgx/v5 (driver, pool), sqlx (thin StructScan), GORM (gorm.io/gorm, full ORM), sqlc (github.com/sqlc-dev/sqlc, codegen from SQL).First signals "not found" via gorm.ErrRecordNotFound, Find via an empty slice with a nil error — mixing the two is a classic.In production the bookshop deploys exactly one binary that must wear three hats: bookstore serve starts the API, bookstore migrate applies schema migrations (via github.com/golang-migrate/migrate/v4 later), and bookstore seed fills the store with test data. In module 10 (lesson 50) you built subcommands with flag.NewFlagSet — at three commands and a growing flag list, that gets tedious: help texts by hand, no completion, no concise configuration logic. That is exactly where Cobra (github.com/spf13/cobra) and Viper (github.com/spf13/viper) come in — the established duo for Go CLIs, from kubectl to hugo.
Cobra provides the structure: every command is a value of type *cobra.Command with Use, Short, and RunE — --help, usage errors, and shell completion fall out automatically. And because RunE returns an error, the main function stays clean: one Execute, one exit code.
// cmd/bookstore/main.go — Cobra: root command plus subcommands
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
)
func main() {
root := &cobra.Command{
Use: "bookstore",
Short: "Manage the bookstore API",
}
serve := &cobra.Command{
Use: "serve",
Short: "Start the HTTP API",
RunE: runServe, // wired up in lesson 60
}
serve.Flags().String("addr", ":8080", "listen address")
migrate := &cobra.Command{
Use: "migrate",
Short: "Apply schema migrations",
RunE: runMigrate,
}
root.AddCommand(serve, migrate)
if err := root.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1)
}
}
// Terminal: bookstore serve --help
// → Start the HTTP API
// →
// → Usage:
// → bookstore serve [flags]
// →
// → Flags:
// → -h, --help help for serve
// → --addr string listen address (default ":8080")
//
// Terminal: bookstore stock
// → Error: unknown command "stock" for "bookstore"
// → Run 'bookstore --help' for usage.
The configuration arrives from four sources, and the order is the quiet star of the show: defaults beat nothing, the file beats defaults, env beats the file, flags beat everything. The same precedence you built by hand in module 10 — now mechanical and consistent. Viper calls this layering; BindPFlag wires Cobra flags so a flag only wins when it was actually set.
// internal/config/config.go — layering: default below file below env below flag
package config
import (
"github.com/spf13/viper"
)
type Config struct {
Addr string `mapstructure:"addr"` // note: mapstructure, not json
DbURL string `mapstructure:"db_url"`
LogLevel string `mapstructure:"log_level"`
}
func Load() (Config, error) {
v := viper.New()
// 1. Defaults — they also register which keys exist
v.SetDefault("addr", ":8080")
v.SetDefault("db_url", "postgres://localhost:5432/bookstore")
v.SetDefault("log_level", "info")
// 2. Config file (optional), e.g. ./bookstore.yaml
v.SetConfigName("bookstore")
v.SetConfigType("yaml")
v.AddConfigPath(".")
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return Config{}, err // file present but unreadable: a hard error
}
}
// 3. Environment variables: BOOKSTORE_ADDR, BOOKSTORE_DB_URL, ...
v.SetEnvPrefix("bookstore")
v.AutomaticEnv()
// 4. main binds flags via v.BindPFlag("addr", serve.Flags().Lookup("addr"))
var cfg Config
if err := v.Unmarshal(&cfg); err != nil {
return Config{}, err
}
return cfg, nil
}
// Terminal: bookstore serve
// → listening on :8080 (default wins, nothing set)
//
// Terminal: BOOKSTORE_ADDR=:9443 bookstore serve
// → listening on :9443 (env beats default)
//
// Terminal: BOOKSTORE_ADDR=:9443 bookstore serve --addr :7070
// → listening on :7070 (flag beats env)
Note the mapstructure tag: Unmarshal runs through github.com/mitchellh/mapstructure — json tags are ignored. Confusing the two tag families gets you a struct full of zero values without a single error message.
⚠ Common mistake: Enabling
AutomaticEnv(), setting NO defaults, and then expectingUnmarshal(&cfg)to deliver. Unmarshal only iterates over keys Viper knows — iflog_levelexists only as the environment variableBOOKSTORE_LOG_LEVEL, the key simply never appears in the struct and stays empty. No error, no log line. The remedy: register every key withSetDefault(as above) or callBindEnvexplicitly — then Unmarshal reliably finds it.
Check: Configuration test: bookstore.yaml says addr: :9000, the shell exports BOOKSTORE_ADDR=:9443, and the invocation is bookstore serve --addr :7070. Which address does the server listen on?
Answer: :7070 — the explicitly set flag beats file and environment
Precedence is strictly ordered: explicit Set in code, then a changed flag, then env, then file, then default. The flag wins here because it was actually set on the command line — a flag that merely exists but was not used would lose to the environment variable. That behavior is what makes container operations predictable: defaults for local work, files per environment, env vars for containers, flags for experiments.
Takeaways:
github.com/spf13/cobra) makes every command a *cobra.Command with RunE — help, usage errors, and completion come for free.github.com/spf13/viper) layers configuration: default below file below env below flag; BindPFlag lets set flags win.Unmarshal needs mapstructure tags and only knows registered keys — without SetDefault, pure env variables silently vanish from the struct.Now the bookshop leaves prototype mode: Gin at the edges (lesson 56), the middleware chain for auth and logging (lesson 57), sqlc on pgx for the data (lesson 58), Cobra and Viper for startup and configuration (lesson 59). The parts are on the bench — the job is wiring them so each stays replaceable on its own. The project grows onto this skeleton:
bookstore/
├── cmd/bookstore/main.go // Cobra: serve, migrate, seed
├── db/
│ ├── migrations/ // SQL schema for golang-migrate AND sqlc
│ ├── query/books.sql // sqlc queries (hand-written)
│ └── sqlc/ // generated: books.sql.go, models.go
├── internal/
│ ├── api/ // Gin router, middleware, handlers
│ ├── catalog/ // domain logic: books, prices, stock
│ └── config/ // Viper layering
└── sqlc.yaml
The sqlc configuration ties queries, schema, and generator together — sql_package: pgx/v5 emits code that talks straight to a pgx pool:
# sqlc.yaml
version: "2"
sql:
- engine: "postgresql"
queries: "db/query"
schema: "db/migrations"
gen:
go:
package: "sqlc"
out: "db/sqlc"
sql_package: "pgx/v5"
The handler is where the crucial translation happens: domain errors become HTTP status codes — and database errors become domain errors. A pgx.ErrNoRows is a 404, not a scandal; a unique violation (pgconn.PgError with code 23505) is a 409, not an internal fire:
// internal/api/books.go — error mapping at the API boundary
package api
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"bookstore/db/sqlc"
)
func (s *Server) handleGetBook(c *gin.Context) {
b, err := s.queries.GetBookByISBN(c.Request.Context(), c.Param("isbn"))
switch {
case errors.Is(err, pgx.ErrNoRows):
c.JSON(http.StatusNotFound, gin.H{"error": "book not found"})
case err != nil:
s.logger.Error("db", "err", err) // details only into the server log
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
default:
c.JSON(http.StatusOK, b)
}
}
func (s *Server) handleCreateBook(c *gin.Context) {
var req struct {
ISBN string `json:"isbn" binding:"required"`
Title string `json:"title" binding:"required"`
}
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
err := s.queries.CreateBook(c.Request.Context(), sqlc.CreateBookParams{
Isbn: req.ISBN, Title: req.Title})
var pgErr *pgconn.PgError
switch {
case errors.As(err, &pgErr) && pgErr.Code == "23505":
c.JSON(http.StatusConflict, gin.H{"error": "ISBN already exists"})
case err != nil:
s.logger.Error("db", "err", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "internal error"})
default:
c.JSON(http.StatusCreated, gin.H{"isbn": req.ISBN})
}
}
// Terminal: curl -s localhost:8080/api/v1/books/978-0-06-231500-7
// → {"isbn":"978-0-06-231500-7","title":"The Alchemist","author":"Paulo Coelho","price_cents":1099,"stock":3}
//
// Terminal: curl -s -o /dev/null -w "%{http_code}" localhost:8080/api/v1/books/000-0-000-00000-0
// → 404
And the serve command that wires it all — one pool, one Queries, one chain, a server with the mandatory timeouts from module 10:
// cmd/bookstore/main.go — serve: pool, queries, router, server
func runServe(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
// ONE pool per process — handlers share it through the server
pool, err := pgxpool.New(cmd.Context(), cfg.DbURL)
if err != nil {
return err
}
defer pool.Close()
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
srv := api.New(sqlc.New(pool), logger) // router + middleware from lesson 57
httpSrv := &http.Server{
Addr: cfg.Addr,
Handler: srv,
ReadHeaderTimeout: 5 * time.Second, // Slowloris protection, lesson 49
WriteTimeout: 15 * time.Second,
}
logger.Info("listening on " + cfg.Addr)
// graceful shutdown exactly as in module 10, lesson 49
return httpSrv.ListenAndServe()
}
// Terminal: the finished API under test
// → $ bookstore serve
// → {"time":"2026-11-05T22:02:11+01:00","level":"INFO","msg":"listening on :8080"}
//
// → $ curl -s -i -X POST localhost:8080/api/v1/books -d '{"isbn":"978-0-06-231500-7","title":"Duplicate"}'
// → HTTP/1.1 409 Conflict
// → {"error":"ISBN already exists"}
//
// → $ curl -s localhost:8080/api/v1/books/978-0-06-231500-7
// → {"isbn":"978-0-06-231500-7","title":"The Alchemist","author":"Paulo Coelho","price_cents":1099,"stock":3}
The store is live: router, middleware, data access, CLI, and configuration from a single cast — and every part stays replaceable because the domain (internal/catalog) knows nothing about any framework. Whether the API holds up under load and real users is module 13's question: Testing & Observability, from github.com/stretchr/testify to OpenTelemetry traces.
⚠ Common mistake: Calling
pgxpool.New(...)inside a handler — a fresh pool per request. Every pool opens its own connections and keeps them open; under load this rips through PostgreSQL'smax_connectionswithin seconds, and every further request dies on a DB error while the database itself is perfectly healthy. The pool is a per-process singleton: open it inrunServe, hand it to handlers through the server struct, close it once viadefer.
Check: GetBookByISBN returns the error pgx.ErrNoRows. Which HTTP status is the correct answer — and why?
Answer: 404 — the client asked for a resource that does not exist; that is their information gain, not our failure
The reflex 'database error equals 500' confuses infrastructure failures with a normal outcome. ErrNoRows means: query correct, answer empty — the client can act on that (drop the book, search differently). A 500 would push it into pointless retries and flood our monitoring with false positives. Only unexpected errors (connection gone, broken syntax) are 500.
Takeaways:
internal/catalog knows none of them.pgx.ErrNoRows becomes 404, pgconn.PgError with code 23505 becomes 409, anything unexpected becomes 500 with details only in the server log.pgxpool opens once per process and is shared — a pool per request shreds database connections under load.sqlc.yaml with sql_package: pgx/v5 ties queries, migrations, and the generator together; the schema and query files remain the single source of truth.Course navigation: ← Module 11 · All 20 modules · Module 13 →