The bookshop grows a microservice mesh: Protobuf contracts with codegen, streaming RPCs in three flavors, interceptors, deadline propagation, and mTLS for daily operations, messaging with NATS JetStream and Kafka (franz-go) including consumer patterns — and distributed consistency with saga and the outbox pattern.
The team's task tracker currently lives as a table in the group chat: nobody knows which tickets are open, and the weekly planning freezes the list every Friday. Time for a small HTTP service anyone can query with curl. In most languages such a project starts with choosing a framework — in Go, net/http from the standard library is enough. No go get, no version chaos, and the experience of many teams after years is: for the majority of services, the built-in router suffices.
Everything revolves around two things. First, the Handler interface: anything with a ServeHTTP(ResponseWriter, *Request) method is a handler — your store, the mux itself, you name it. Second, http.ServeMux, which since Go 1.22 is a real router: patterns can combine HTTP methods, literal segments, and wildcards, and the most specific pattern wins.
A Handler Is an Interface with One Method
net/http demands no base class and no framework. A type implementing ServeHTTP(w, r) is a full handler; an ordinary function becomes one via http.HandlerFunc or mux.HandleFunc. That is exactly why everything can be wired as a handler — the mux, a FileServer, your own struct — and why middleware (lesson 48) works without any magic.
Here is the smallest useful server — with a method pattern and a wildcard:
// hello/main.go
package main
import (
"fmt"
"net/http"
)
func main() {
mux := http.NewServeMux()
// Since Go 1.22: HTTP method and wildcard directly in the pattern
mux.HandleFunc("GET /hello/{name}", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.PathValue("name"))
})
mux.HandleFunc("GET /health", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("ok"))
})
fmt.Println("Server running at http://localhost:8080")
if err := http.ListenAndServe(":8080", mux); err != nil {
fmt.Println("server exited:", err)
}
}
// Terminal: curl http://localhost:8080/hello/Ada
// → Hello, Ada!
//
// Terminal: curl http://localhost:8080/health
// → ok
http.ListenAndServe starts the server and blocks until it stops (clean shutdown follows in lesson 49). Passing nil as the handler uses the DefaultServeMux — for your own routing, build a fresh mux and pass it along.
Now the actual service. Two things stand out in the patterns: "POST /tasks" matches only POST requests — a DELETE against that route is answered by the mux automatically with 405 Method Not Allowed, including an Allow header. And {id} captures exactly one segment, readable via r.PathValue("id"). A wildcard happily matches non-numbers too, so the handler validates it itself and answers with http.Error — the built-in helper for text errors with a status code.
Note the sync.Mutex in the store as well. That is not a style detail but survival equipment — more on that in a moment.
// taskd/main.go
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"sync"
)
// Task is one row in the task tracker.
type Task struct {
ID int `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
// Store keeps tasks in memory. The mutex is mandatory:
// net/http serves every request in its own goroutine.
type Store struct {
mu sync.Mutex
tasks map[int]Task
next int
}
func (s *Store) Add(title string) Task {
s.mu.Lock()
defer s.mu.Unlock()
s.next++
t := Task{ID: s.next, Title: title}
s.tasks[t.ID] = t
return t
}
func (s *Store) Get(id int) (Task, bool) {
s.mu.Lock()
defer s.mu.Unlock()
t, ok := s.tasks[id]
return t, ok
}
func main() {
store := &Store{tasks: map[int]Task{}}
mux := http.NewServeMux()
mux.HandleFunc("POST /tasks", func(w http.ResponseWriter, r *http.Request) {
// JSON decoding follows in lesson 47
t := store.Add("new task")
fmt.Fprintf(w, "created: #%d %s", t.ID, t.Title)
})
mux.HandleFunc("GET /tasks/{id}", func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil {
http.Error(w, "id must be a number", http.StatusBadRequest)
return
}
if t, ok := store.Get(id); ok {
fmt.Fprintf(w, "#%d %s (done: %v)", t.ID, t.Title, t.Done)
return
}
http.NotFound(w, r)
})
log.Println("taskd listening on :8080")
log.Fatal(http.ListenAndServe(":8080", mux))
}
// Terminal: curl http://localhost:8080/tasks/1
// → #1 new task (done: false)
//
// Terminal: curl -i http://localhost:8080/tasks/abc
// → HTTP/1.1 400 Bad Request
// → id must be a number
//
// Terminal: curl -i -X DELETE http://localhost:8080/tasks/1
// → HTTP/1.1 405 Method Not Allowed
// → Allow: GET
Pattern selection follows one rule: the more specific pattern wins — a literal segment like export beats {id}, and {id} beats the catch-all under /. Register two identical patterns and the mux panics immediately at startup. That sounds harsh, but it is a gift: routing conflicts surface at boot, not at 3 a.m. with the first request.
⚠ Common mistake: Building the store as a bare
map[int]Taskwithout synchronization.net/httpserves every request in its own goroutine — as soon as two concurrent POSTs write to the map, it is not the request that crashes but the entire process, withfatal error: concurrent map writes. Go maps are not safe for concurrent use: async.Mutexaround every access (as in the store above) belongs on any state shared between handlers.
Check: Registered: GET /tasks/{id} and GET /tasks/export. A request arrives for GET /tasks/export — which handler fires?
Answer: GET /tasks/export — the literal segment is more specific than {id} and wins
Since Go 1.22 the ServeMux picks the most specific pattern per request: literal segments beat wildcards, wildcards beat broader prefixes. A true conflict — two identical patterns — would already have panicked at registration time, not at runtime.
Takeaways:
net/http needs no framework: since Go 1.22 the ServeMux combines methods, wildcards ({id}), and literal segments in patterns.ServeHTTP — functions join via mux.HandleFunc, types via implementing the method.sync.Mutex — otherwise fatal error: concurrent map writes.The service from lesson 46 still speaks plain text. That is fine for curl, but the frontend team and the other services want JSON — with a clearly defined contract: Which fields does a task have? What happens on a typo in a field name? Which status code does the client get when the title is missing? This lesson turns the text endpoint into a JSON API with strict validation.
For sending we use json.NewEncoder(w).Encode(v): the encoder writes directly to the ResponseWriter without buffering the body in a byte slice in RAM first. For receiving we work with json.NewDecoder(r.Body) — the same pattern as the LLM client in module 4, just in the other direction. And we switch to strict mode with DisallowUnknownFields: fields the struct does not know then count as errors instead of silently ignored data.
Status Codes Tell the Client Who Made the Mistake
Three classes, three codes: 400 means "your JSON is broken or violates the schema" — the client can fix the request itself. 422 means "JSON fine, content not allowed" — an empty title, say. 500 means "the problem is on my side" — the client can only retry later. Answering everything with 500 forces clients into pointless retries and sends you on a wild goose chase.
The handler for POST /tasks — with validation, a Location header, and the right status codes:
// api/tasks.go
package api
import (
"encoding/json"
"net/http"
"strconv"
"strings"
)
// writeJSON sets headers and status BEFORE encoding.
func writeJSON(w http.ResponseWriter, status int, v any) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
func (s *Server) handleCreateTask(w http.ResponseWriter, r *http.Request) {
var req struct {
Title string `json:"title"`
}
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(&req); err != nil {
// Class 1: unreadable or off-schema JSON
writeJSON(w, http.StatusBadRequest,
map[string]string{"error": "unreadable JSON: " + err.Error()})
return
}
// Class 2: JSON valid, content forbidden
req.Title = strings.TrimSpace(req.Title)
if req.Title == "" {
writeJSON(w, http.StatusUnprocessableEntity,
map[string]string{"error": "title must not be empty"})
return
}
task := s.store.Add(req.Title)
w.Header().Set("Location", "/tasks/"+strconv.Itoa(task.ID))
writeJSON(w, http.StatusCreated, task)
}
// Terminal: curl -i -X POST localhost:8080/tasks -d '{"title":"Review on-call rotation"}'
// → HTTP/1.1 201 Created
// → Content-Type: application/json
// → Location: /tasks/7
// → {"id":7,"title":"Review on-call rotation","done":false}
The difference between the classes is not cosmetics but debugging time. One curl session against the finished API shows all three:
// Terminal: the three error classes compared
//
// broken JSON (syntax error) → 400
// → $ curl -s -i -X POST localhost:8080/tasks -d '{"title":'
// → HTTP/1.1 400 Bad Request
// → {"error":"unreadable JSON: unexpected EOF"}
//
// unknown field (schema violation thanks to DisallowUnknownFields) → 400
// → $ curl -s -i -X POST localhost:8080/tasks -d '{"titel":"typo"}'
// → HTTP/1.1 400 Bad Request
// → {"error":"unreadable JSON: json: unknown field \"titel\""}
//
// valid JSON, forbidden content → 422
// → $ curl -s -i -X POST localhost:8080/tasks -d '{"title":" "}'
// → HTTP/1.1 422 Unprocessable Entity
// → {"error":"title must not be empty"}
Without DisallowUnknownFields the second case would slip through silently: the titel typo would be ignored, Title would stay empty, and the client would receive a 422 saying "title must not be empty" — a misleading error message far away from the actual cause. Strict decoding turns the typo into an immediate, precise response. For field semantics beyond "not empty" (formats, lengths, ranges), a hand-written validate method usually suffices — Go developers reach for validation frameworks only once the rules exceed a dozen.
⚠ Common mistake: Calling
w.Header().Set("Content-Type", "application/json")only AFTERw.WriteHeader(...)or the firstWrite. Headers leave with the status — the laterSetis silently ignored. The client then guesses via content sniffing (usuallytext/plain), and strict JSON clients fail with cryptic parse errors even though the body is perfect. Always: set headers, then status, then body.
Check: A POST body contains the field titel (a typo) instead of title. What happens when decoding into a struct with the field Title — without DisallowUnknownFields?
Answer: Nothing — the field is silently ignored, Title stays empty, and the request counts as valid
encoding/json silently ignores unknown fields. That is exactly what makes the bug so sneaky: the client sent a typo, but the API complains much later and somewhere else that the title is empty. DisallowUnknownFields flips this — the typo is reported immediately as a 400 naming the field.
Takeaways:
json.NewEncoder(w).Encode(v) streams the response straight into the ResponseWriter — no byte slices in RAM.DisallowUnknownFields makes the API strict: typos in field names become precise 400s instead of silently ignored data.Content-Type and Location before writing status and body — afterwards the header is already on its way.The service runs stable for two weeks — until the report endpoint dereferences a nil field for one particular query and panics. What happens? The process does not die: net/http recovers panics per connection and logs http: panic serving. But the client gets no clean 500 response, only a dropped connection — and the access log contains no line for that request. At 3 a.m. you want to know exactly two things: which route was it, and how long did it run.
The answer is middleware: a function that wraps a handler and returns a new one — func(http.Handler) http.Handler. No framework, no interface hierarchy, no magic. Middleware can work before the call (log the request, check the body), watch the call itself (recover, timeouts), and clean up after it.
Middleware Is a Function — Order Is Execution Order
Stacked, middleware forms an onion: with Chain(mux, Recovery, Logging) a request passes through Recovery first, then Logging, then the handler — and the response travels back out in reverse. Whatever sits on the outside sees everything below it: Recovery therefore also catches panics from the logging middleware, not just from handlers. Reverse the order and you reverse the responsibility.
Logging first. The only hurdle: the ResponseWriter does not report the status code it was given back to the caller. The fix is a small wrapper struct that intercepts WriteHeader and records it:
// middleware/middleware.go
package middleware
import (
"log"
"net/http"
"time"
)
// Middleware wraps a handler and returns a new one.
type Middleware func(http.Handler) http.Handler
// Chain stacks middleware: Chain(h, A, B) yields A(B(h)) —
// A sits on the outside and runs first.
func Chain(h http.Handler, mw ...Middleware) http.Handler {
for i := len(mw) - 1; i >= 0; i-- {
h = mw[i](h)
}
return h
}
// statusRecorder remembers the status code set by the inner handler.
type statusRecorder struct {
http.ResponseWriter
status int
}
func (r *statusRecorder) WriteHeader(code int) {
r.status = code
r.ResponseWriter.WriteHeader(code)
}
func WithLogging(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}
next.ServeHTTP(rec, r)
log.Printf("%s %s -> %d (%s)",
r.Method, r.URL.Path, rec.status, time.Since(start).Round(time.Microsecond))
})
}
// Terminal: curl localhost:8080/tasks
// → 2026/11/05 21:14:03 GET /tasks -> 200 (213µs)
An honest note: for streaming responses the recorder would also have to forward Flush() (see http.Flusher, module 4). For JSON responses written in one piece it works exactly as shown.
Recovery middleware uses nothing but defer/recover and runtime/debug.Stack() — and turns a panic into a clean 500 response with a stack trace in the server log:
// middleware/recovery.go
package middleware
import (
"encoding/json"
"log"
"net/http"
"runtime/debug"
)
func WithRecovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("panic in %s %s: %v\n%s",
r.Method, r.URL.Path, err, debug.Stack())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": "internal error"})
}
}()
next.ServeHTTP(w, r)
})
}
// server/main.go — wiring: Recovery outside, Logging inside
func main() {
mux := newMux() // the routes from lessons 46 and 47
handler := middleware.Chain(mux, middleware.WithRecovery, middleware.WithLogging)
log.Println("server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", handler))
}
// Terminal: curl -s -i localhost:8080/report/huge
// → HTTP/1.1 500 Internal Server Error
// → {"error":"internal error"}
//
// Server log, stack trace trimmed:
// → panic in GET /report/huge: runtime error: invalid memory address or nil pointer dereference
The third standard element is timeouts. Not every handler is fast: a report calling out over http.Client can hang while the client is long gone. http.TimeoutHandler stops individual routes after a deadline and answers with 503:
// Per-route timeout: after 5s of processing, we are done
mux.Handle("GET /report", http.TimeoutHandler(
reportHandler,
5*time.Second,
`{"error":"processing took too long"}`,
))
// Terminal: curl -s -i --max-time 10 localhost:8080/report
// → HTTP/1.1 503 Service Unavailable
// → {"error":"processing took too long"}
Add the server-wide timeouts from the next lesson — TimeoutHandler bounds processing time per route, while ReadHeaderTimeout and friends bound the connection itself.
⚠ Common mistake: Logging middleware that reads the request body for audit logs — say via
io.ReadAll(r.Body)— and never restores it. The nextDecodein the handler then reads EOF: every POST arrives with an empty body, and the validation from lesson 47 reports "title must not be empty" even though the client sent everything correctly. If middleware must read the body: read it, then setr.Body = io.NopCloser(bytes.NewReader(buf))before callingnext.ServeHTTP.
Check: Setup: Chain(mux, WithRecovery, WithLogging) — WithRecovery sits on the outside. A handler panics. What do you observe?
Answer: The client gets a 500 response, but the request never appears in WithLogging's log
The panic unwinds from the inside out: the code after next.ServeHTTP in WithLogging is never reached, so the log line is missing. Only WithRecovery catches the panic on the outside and answers with 500. That is exactly why Recovery belongs on the outside — and if you want panics in the access log too, you must handle them in the logging middleware itself.
Takeaways:
func(http.Handler) http.Handler — stacked it forms an onion, and the order is the execution order.statusRecorder wrapper because the ResponseWriter does not report the status code back.http.TimeoutHandler bounds individual routes; middleware that reads the body must restore it for the handler.On Monday at 2:32 p.m. Kubernetes rolls out the new version and sends SIGTERM. The naive server dies mid-flight — and a request that was just writing a task to the database is left half-finished. Graceful shutdown is the difference between "deploy" and "data loss": refuse new requests, let running ones finish in peace, then exit.
The tool for this is signal.NotifyContext: it turns SIGINT (Ctrl+C) and SIGTERM (containers, systemd) into an ordinary context cancellation — the same mechanism we have used since module 7 for timeouts and aborts. Along with it comes the http.Server value instead of the http.ListenAndServe one-liner, because only the type carries Shutdown and the timeouts.
Graceful Shutdown Is a Three-Part Contract
First: close the listeners immediately — new connections are refused. Second: let running requests drain — the store may finish its transaction. Third: give up after a deadline — Shutdown then returns the context's error. The deadline matters because a hanging request would otherwise block shutdown until the orchestrator eventually sends SIGKILL, which is even less merciful.
The complete production main — signal handling, server configuration, and an orderly drain:
// taskd/main.go
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
srv := &http.Server{
Addr: ":8080",
Handler: newHandler(), // mux + middleware from lesson 48
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
// Subscribe to SIGINT (Ctrl+C) and SIGTERM (containers)
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
errCh := make(chan error, 1)
go func() {
// ErrServerClosed arrives on clean shutdown — that is NOT an error
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
errCh <- err
}
}()
select {
case err := <-errCh:
log.Fatalf("server error: %v", err)
case <-ctx.Done():
log.Println("signal received — letting running requests drain")
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil {
log.Printf("deadline expired, forcing stop: %v", err)
}
}
log.Println("server shut down cleanly")
}
// Terminal: Ctrl+C while a slow GET /report is still running
// → 2026/11/05 21:30:01 server listening on :8080
// → 2026/11/05 21:31:44 signal received — letting running requests drain
// → 2026/11/05 21:31:46 GET /report -> 200 (3.9s) ← the request was allowed to finish
// → 2026/11/05 21:31:46 server shut down cleanly
Shutdown is the standard path, but not the only tool. And the server timeouts are not optional — they are armor against attacks and misbehaving clients:
// Shutdown or Close?
//
// srv.Shutdown(ctx) // close listeners now; let running requests drain,
// // at most until ctx expires — the standard path
// srv.Close() // drop ALL connections IMMEDIATELY — emergency
// // brake; running requests break mid-body
//
// And without the timeouts the server is open to Slowloris:
// a client sending headers in slow motion otherwise holds
// connections and file descriptors open indefinitely.
srv := &http.Server{
Addr: ":8080",
Handler: handler,
ReadHeaderTimeout: 5 * time.Second, // Slowloris protection
ReadTimeout: 10 * time.Second, // time for the complete request
WriteTimeout: 15 * time.Second, // time for the response
IdleTimeout: 60 * time.Second, // keep-alive pause between requests
}
// Terminal: a client sending headers in slow motion (Slowloris)
// → curl: (28) Operation timed out — the server cuts it off after 5 seconds
Finally, an honest look at BaseContext and friends: once individual handlers may run for minutes (long exports), it pays to respect r.Context() inside them — a client that has gone away should stop the handler too. That is not special shutdown logic but ordinary context discipline from module 7.
⚠ Common mistake:
log.Fatal(http.ListenAndServe(":8080", mux))on the main goroutine. On every clean shutdownListenAndServereturns the expectedhttp.ErrServerClosed— andlog.Fataltreats the successful rollout as a crash: exit code 1, a 3 a.m. alert, a red deploy pipeline. Correct: runListenAndServein a goroutine, check the error, and treaterrors.Is(err, http.ErrServerClosed)as success.
Check: srv.Shutdown(ctx) is running, but after ctx expires a request is still in flight. What happens?
Answer: Shutdown returns the context error; the goroutine keeps running until it ends on its own
Go cannot kill goroutines from the outside. Shutdown only waits until the context expires and then reports its error — the stuck handler silently keeps running until it finishes by itself. To stop immediately, call srv.Close() afterwards and cut connections hard; better still, build long-running handlers to respect r.Context() and their own timeouts.
Takeaways:
signal.NotifyContext turns SIGINT/SIGTERM into an ordinary context cancellation — the same abort pattern as everywhere else in Go.srv.Shutdown(ctx) closes listeners immediately and lets running requests drain within a deadline; srv.Close() is the hard emergency brake.http.ErrServerClosed from ListenAndServe is the success path — treating it as fatal pages you on every deploy.http.Server timeouts (ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout) are production requirements, especially against Slowloris.The server is only half the story. Ops wants to start it, you want to test it locally, and at the end of the deploy pipeline stands a single binary that fits into any container. Go services are therefore traditionally shipped as a CLI with subcommands: tasksrv serve starts the API, tasksrv version tells you what is inside the container. The standard library's flag package provides subcommands and flags without a single dependency — for tools of this size it is entirely sufficient.
The pattern is always the same: os.Args[1] selects the command, each command gets its own flag.NewFlagSet and parses only its own slice of arguments.
Flags for Humans, Environment Variables for Machines
On the console you type --addr :7070; in a container the configuration arrives as an environment variable. The established precedence: flag beats env, env beats default. Technically it is one line — the flag's default already is the env value: whoever sets the flag wins; whoever only sets the variable gets it; whoever sets nothing gets the fixed default.
// main.go — one binary, several commands
package main
import (
"flag"
"fmt"
"os"
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "usage: tasksrv (serve|version) [flags]")
os.Exit(2)
}
switch os.Args[1] {
case "serve":
cmdServe(os.Args[2:])
case "version":
fmt.Println("tasksrv v1.4.0")
default:
fmt.Fprintln(os.Stderr, "unknown command:", os.Args[1])
os.Exit(2)
}
}
func cmdServe(args []string) {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
addr := fs.String("addr", envOrDefault("TASKSRV_ADDR", ":8080"), "listen address")
fs.Parse(args)
fmt.Println("tasksrv listening on", *addr)
runServer(*addr) // the finished server from lessons 46 to 49
}
// Terminal: go run . serve --addr :9090
// → tasksrv listening on :9090
//
// Terminal: go run . version
// → tasksrv v1.4.0
//
// Terminal: go run . help
// → unknown command: help (exit code 2)
flag.ExitOnError provides useful automation: a bad flag prints the flag set's usage and exits with code 2 — exactly the code by which scripts recognize a user error. Prefer to handle it yourself? Choose flag.ContinueOnError and inspect the error returned by fs.Parse.
The env fallback helper is deliberately unspectacular — three lines, no dependency:
// config/config.go
package config
import "os"
// envOrDefault returns the environment variable's value or the default.
func envOrDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
// The default of the -addr flag already is the env value: precedence
// flag over env over default, with no extra logic.
func serveFlags(args []string) *flag.FlagSet {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
fs.String("addr", envOrDefault("TASKSRV_ADDR", ":8080"), "listen address")
return fs
}
// Terminal: TASKSRV_ADDR=:9443 go run . serve
// → tasksrv listening on :9443
//
// Terminal: TASKSRV_ADDR=:9443 go run . serve --addr :7070
// → tasksrv listening on :7070
With that, the toolbox is complete. The capstone connects the pieces: the router from lesson 46, the JSON contracts from lesson 47, the middleware trio from lesson 48, the signal handling from lesson 49 — started through the CLI of this lesson. A stress test from the outside:
// Terminal: the finished capstone in action
//
// → $ tasksrv serve --addr :8080
// → tasksrv listening on :8080
//
// → $ curl -s -X POST localhost:8080/tasks -d '{"title":"Ship the capstone"}'
// → created: #1 Ship the capstone
//
// → $ curl -s localhost:8080/tasks/1
// → #1 Ship the capstone (done: false)
//
// → $ curl -s -i -X POST localhost:8080/tasks -d '{"titel":"typo"}'
// → HTTP/1.1 400 Bad Request
// → {"error":"unreadable JSON: json: unknown field \"titel\""}
//
// → $ tasksrv version
// → tasksrv v1.4.0
From the first curl answer to here took five lessons — and not a line of framework code. That is exactly the strength of net/http: the convenient path and the correct path are the same.
⚠ Common mistake: Putting flags after positional arguments.
tasksrv import --verbose old.xmlworks;tasksrv import old.xml --verbosedoes not: theflagparser stops at the first argument that does not start with-—--verboselands unparsed infs.Args()as if it were a file. Flags belong before the positional arguments; if you dislike that, inspectfs.Args()yourself or reach for a library with GNU-style parsing.
Check: The invocation is: tasksrv serve --addr :9090 export.csv. What does fs.Args() contain after fs.Parse(os.Args[2:])?
Answer: export.csv — the positional arguments after the flags
fs.Parse consumes --addr and its value, then stops at export.csv, the first positional argument. Everything from there on is by definition positional — which is why in practice you check len(fs.Args()) before touching fs.Args()[0] instead of wondering later why the value came from the wrong slot.
This closes the Go course: from the first fmt.Println in module 1 through slices, structs, goroutines, error handling, and testing, to a service that starts, answers, and shuts down in production. Module 10 filled the last gap — HTTP and CLI, both with the standard library.
Weekly check: do you have these points down?
signal.NotifyContext and handle http.ErrServerClosed correctly?Takeaways:
ServeMux handles methods, wildcards, and precedence — handlers are just a one-method interface, and shared state needs a mutex.Encoder/Decoder straight on the stream, DisallowUnknownFields for strict contracts, and status codes (400/422/500) that tell the client who made the mistake.func(http.Handler) http.Handler is all it takes for logging (with a status recorder), recovery (outermost!), and per-route timeouts.signal.NotifyContext plus srv.Shutdown(ctx) let deploys drain without data loss; ErrServerClosed is success, server timeouts are mandatory.flag.NewFlagSet, precedence flag over env over default — and as the capstone, the complete REST service from a single hand.Course navigation: ← Module 9 · All 20 modules · Module 11 →