The Analogy: The Reception Desk
A visitor walks into an office building. They do not wander the corridors looking for the person they need; they stop at reception. The receptionist reads the directory board, works out which department handles this kind of business, and sends the visitor there. The department deals with the request, writes a reply on headed paper, and hands it back. If the directory has no entry, the visitor is turned away at the desk without ever reaching a corridor.
Everyone passes the security desk on the way in. Badges are checked, arrivals are recorded in a book, and anyone without a badge is stopped there -- once, at the entrance, rather than by each department inventing its own check. The order of the desks is the whole design: security before the directory means nobody unbadged reaches a department, and the arrivals book sitting outside security means even the rejections are recorded.
Go's net/http is that building, with one twist that shapes everything else: every visitor gets their own receptionist. The server runs each request in its own goroutine, so a handler is not a single-threaded routine that processes requests one after another -- it is code that may be executing in a hundred copies simultaneously, all sharing the same package variables. That is why every piece of state a handler touches has to be safe for concurrent use.
The other half of the lesson is the same building seen from outside: your program as the visitor. Sending a request means constructing it with a return address and a deadline, handing it to a courier you keep and reuse rather than hiring a new one each time, and -- the detail that causes the most production incidents -- always closing the envelope when you are done reading it, so the courier can use that route again.
Syntax or Core Structure
package main
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
"time"
)
func main() {
mux := http.NewServeMux()
// Since Go 1.22 the method and the wildcards live in the pattern itself.
mux.HandleFunc("GET /items/{id}", func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
w.Header().Set("Content-Type", "application/json") // 1. headers
w.Header().Set("X-Item", id)
w.WriteHeader(http.StatusOK) // 2. status
fmt.Fprintf(w, `{"id":%q,"stock":7}`, id) // 3. body
})
mux.HandleFunc("POST /items/{id}", func(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<10))
if err != nil {
http.Error(w, "body too large", http.StatusRequestEntityTooLarge)
return
}
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, "stored %d bytes for %s", len(body), r.PathValue("id"))
})
ln, err := net.Listen("tcp", "127.0.0.1:0") // port 0: the OS picks a free one
if err != nil {
panic(err)
}
srv := &http.Server{
Handler: mux,
ReadHeaderTimeout: 5 * time.Second, // ListenAndServe sets none of these
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() { _ = srv.Serve(ln) }()
base := "http://" + ln.Addr().String()
client := &http.Client{Timeout: 5 * time.Second}
call(client, "GET", base, "/items/kb-01", "")
call(client, "GET", base, "/items/kb-01/extra", "")
call(client, "POST", base, "/items/kb-01", "count=2")
call(client, "DELETE", base, "/items/kb-01", "")
call(client, "GET", base, "/missing", "")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(ctx)
}
func call(c *http.Client, method, base, p, body string) {
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
req, err := http.NewRequestWithContext(context.Background(), method, base+p, rdr)
if err != nil {
fmt.Println("build:", err)
return
}
resp, err := c.Do(req)
if err != nil {
fmt.Println("do:", err) // only transport failures land here
return
}
defer resp.Body.Close() // on every path, always
out, _ := io.ReadAll(resp.Body)
fmt.Printf("%-6s %-22s -> %d %s\n", method, p, resp.StatusCode, strings.TrimSpace(string(out)))
if v := resp.Header.Get("X-Item"); v != "" {
fmt.Printf(" X-Item: %s | Content-Type: %s\n", v, resp.Header.Get("Content-Type"))
}
}
Output:
GET /items/kb-01 -> 200 {"id":"kb-01","stock":7}
X-Item: kb-01 | Content-Type: application/json
GET /items/kb-01/extra -> 404 404 page not found
POST /items/kb-01 -> 201 stored 7 bytes for kb-01
DELETE /items/kb-01 -> 405 Method Not Allowed
GET /missing -> 404 404 page not found
Four routing outcomes from two registered patterns. /items/kb-01 matched. /items/kb-01/extra did not, because {id} matches exactly one path segment and never a slash. DELETE produced 405 rather than 404 because the path matched a registered pattern under a different method -- the mux distinguishes "no such resource" from "not that verb", and sets an Allow header on the 405 telling the client which verbs exist.
Technical Depth: Handlers, Patterns, Timeouts
One interface, one adapter
type Handler interface {
ServeHTTP(w ResponseWriter, r *Request)
}
type HandlerFunc func(ResponseWriter, *Request)
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { f(w, r) }
That is the entire extension point. ServeMux is a Handler, middleware is a Handler wrapping a Handler, and HandlerFunc exists only so an ordinary function can satisfy the interface. http.Handle takes the interface; http.HandleFunc performs the conversion for you.
Routing patterns since Go 1.22
| Pattern | Matches |
|---|---|
/items | that exact path only |
/items/ | /items/ and everything beneath it |
/items/{id} | exactly one further segment, readable as r.PathValue("id") |
/files/{rest...} | all remaining segments, slashes included |
/items/{$} | /items/ exactly, blocking the subtree match |
GET /items/{id} | method-scoped; GET also serves HEAD |
example.com/items | host-scoped |
The most specific pattern wins regardless of registration order, and two patterns that overlap without one being more specific panic at registration time rather than resolving silently. A wildcard name may appear only once per pattern.
ResponseWriter has one legal order
Set headers, then call WriteHeader, then write the body. WriteHeader freezes the header map: anything you set afterwards is discarded, and a second WriteHeader logs "superfluous response.WriteHeader call" and is ignored. The first Write implicitly sends 200, which is why an error path must return immediately after writing its response -- otherwise the handler falls through and tries to write a second status.
if err != nil {
http.Error(w, "not found", http.StatusNotFound) // sets Content-Type, status, body
return // without this, the 200 below wins
}
w.Write(payload)
If Content-Type is not set explicitly, the server sniffs it from the first 512 bytes.
The server struct is the production config
| Field | Guards against |
|---|---|
ReadHeaderTimeout | a client that opens a connection and dribbles headers forever (slowloris) |
ReadTimeout | a slow or endless request body |
WriteTimeout | a client that stops reading your response |
IdleTimeout | keep-alive connections held open doing nothing |
MaxHeaderBytes | header floods; the default is 1 MB |
http.ListenAndServe(addr, h) sets none of these, which is why it belongs in examples and not in services. Construct an &http.Server{} and call its own ListenAndServe, or Serve on a listener you created.
Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Printf("forced close: %v", err)
}
Shutdown stops accepting, closes idle connections, and waits for active handlers to return. It does not cancel in-flight request contexts -- srv.RegisterOnShutdown or a separate cancellable context is how you tell handlers to hurry up. Serve returns http.ErrServerClosed on a clean shutdown, which is a success, not a failure.
Client rules that cost people real outages
| Rule | Why |
|---|---|
Always defer resp.Body.Close() | an unclosed body leaks the connection and its goroutines |
| Drain the body before closing | a partially read body cannot be reused for keep-alive |
Reuse one *http.Client | a new Transport per request means a new pool, so zero connection reuse |
resp.StatusCode is not err | Do returns nil error for a 500; only transport failures produce one |
Prefer a context deadline over Client.Timeout | Timeout covers the whole exchange including body reads, and cannot be varied per call |
Raise Transport.MaxIdleConnsPerHost | the default of 2 throttles a busy client against a single host |
http.Get and friends use http.DefaultClient, which has no timeout at all -- a hung server hangs your program indefinitely.
Anything reachable is public unless a handler says otherwise
A ServeMux on a listening port answers anyone who can route to it. net/http provides no authentication, no rate limiting and no request size cap beyond headers. Every mutating route needs an explicit check in front of it, request bodies need http.MaxBytesReader, and binding to 127.0.0.1 rather than 0.0.0.0 is the difference between a local development server and one exposed to your whole network.
Testing without a network
httptest.NewRecorder() lets you call ServeHTTP directly and assert on the recorded status, headers and body. httptest.NewServer(handler) starts a real server on a real loopback port and gives you ts.URL, which is how you test a client. Both need no ports of your choosing and no cleanup beyond defer ts.Close().
Real World Example: A JSON API With a Middleware Chain
A small authenticated API: request ids, an access log, panic recovery, bearer-token auth, and two handlers over shared state. Every one of those concerns is a func(http.Handler) http.Handler, which is the only composition mechanism net/http needs.
package main
import (
"context"
"crypto/subtle"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
)
type Item struct {
SKU string `json:"sku"`
Name string `json:"name"`
Stock int `json:"stock"`
}
// store is shared by every request goroutine, so it carries its own lock.
type store struct {
mu sync.RWMutex
items map[string]Item
}
func (s *store) get(sku string) (Item, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
it, ok := s.items[sku]
return it, ok
}
func (s *store) put(it Item) {
s.mu.Lock()
defer s.mu.Unlock()
s.items[it.SKU] = it
}
func writeJSON(w http.ResponseWriter, status int, v any) {
body, err := json.Marshal(v)
if err != nil {
http.Error(w, "encode failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write(body)
}
func (s *store) handleGet(w http.ResponseWriter, r *http.Request) {
it, ok := s.get(r.PathValue("sku"))
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such item"})
return
}
writeJSON(w, http.StatusOK, it)
}
func (s *store) handlePut(w http.ResponseWriter, r *http.Request) {
var in Item
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<16))
dec.DisallowUnknownFields() // a typo in the payload is a 400, not a silent ignore
if err := dec.Decode(&in); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
return
}
in.SKU = r.PathValue("sku") // the URL is authoritative, never the body
s.put(in)
writeJSON(w, http.StatusOK, in)
}
// --- the log sink: collected rather than printed, so this program's output is
// reproducible. A real service would write to a logger here.
var (
logMu sync.Mutex
logLines []string
)
func logf(format string, args ...any) {
logMu.Lock()
defer logMu.Unlock()
logLines = append(logLines, fmt.Sprintf(format, args...))
}
// --- middleware
type ctxKeyReqID struct{}
func reqID(ctx context.Context) string {
id, _ := ctx.Value(ctxKeyReqID{}).(string)
return id
}
var nextID atomic.Int64
func requestID(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id := fmt.Sprintf("req-%03d", nextID.Add(1))
w.Header().Set("X-Request-Id", id)
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKeyReqID{}, id)))
})
}
// statusWriter remembers what the handler below actually sent.
type statusWriter struct {
http.ResponseWriter
status int
n int
}
func (sw *statusWriter) WriteHeader(code int) {
sw.status = code
sw.ResponseWriter.WriteHeader(code)
}
func (sw *statusWriter) Write(b []byte) (int, error) {
if sw.status == 0 {
sw.status = http.StatusOK // the implicit 200 of a bare Write
}
n, err := sw.ResponseWriter.Write(b)
sw.n += n
return n, err
}
func logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
sw := &statusWriter{ResponseWriter: w}
next.ServeHTTP(sw, r)
logf(" %-8s %-6s %-18s %d %dB", reqID(r.Context()), r.Method, r.URL.Path, sw.status, sw.n)
})
}
func recoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if v := recover(); v != nil {
logf(" %-8s panic recovered: %v", reqID(r.Context()), v)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal"})
}
}()
next.ServeHTTP(w, r)
})
}
// requireToken is the only thing between these handlers and anyone who can
// reach the port. Remove it and the API is public, including the writes.
func requireToken(token string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got, found := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
if !found || subtle.ConstantTimeCompare([]byte(got), []byte(token)) != 1 {
w.Header().Set("WWW-Authenticate", `Bearer realm="items"`)
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return
}
next.ServeHTTP(w, r)
})
}
}
// chain applies middleware so that the first listed is the outermost.
func chain(h http.Handler, mw ...func(http.Handler) http.Handler) http.Handler {
for i := len(mw) - 1; i >= 0; i-- {
h = mw[i](h)
}
return h
}
func call(c *http.Client, method, base, p, token, body string) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
var rdr io.Reader
if body != "" {
rdr = strings.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, base+p, rdr)
if err != nil {
fmt.Println("build request:", err)
return
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
resp, err := c.Do(req)
if err != nil {
fmt.Println("call failed:", err)
return
}
defer resp.Body.Close()
out, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if err != nil {
fmt.Println("read body:", err)
return
}
fmt.Printf("%-6s %-18s -> %-3d %s\n", method, p, resp.StatusCode, out)
}
func main() {
const token = "s3cr3t-token"
s := &store{items: map[string]Item{
"kb-01": {SKU: "kb-01", Name: "Keyboard", Stock: 4},
}}
mux := http.NewServeMux()
mux.HandleFunc("GET /v1/items/{sku}", s.handleGet)
mux.HandleFunc("PUT /v1/items/{sku}", s.handlePut)
mux.HandleFunc("GET /v1/boom", func(_ http.ResponseWriter, _ *http.Request) {
panic("simulated handler failure")
})
// Outermost first: an unauthorised request still gets an id and a log line.
handler := chain(mux, requestID, logging, recoverPanic, requireToken(token))
ln, err := net.Listen("tcp", "127.0.0.1:0") // loopback only, not 0.0.0.0
if err != nil {
panic(err)
}
srv := &http.Server{
Handler: handler,
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 15 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
go func() { _ = srv.Serve(ln) }()
base := "http://" + ln.Addr().String()
client := &http.Client{Timeout: 5 * time.Second} // one client, reused for all calls
call(client, "GET", base, "/v1/items/kb-01", "", "")
call(client, "GET", base, "/v1/items/kb-01", token, "")
call(client, "GET", base, "/v1/items/zz-99", token, "")
call(client, "PUT", base, "/v1/items/kb-01", token, `{"name":"Keyboard","stock":9,"colour":"black"}`)
call(client, "PUT", base, "/v1/items/kb-01", token, `{"name":"Keyboard","stock":9}`)
call(client, "GET", base, "/v1/boom", token, "")
shutCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(shutCtx); err != nil {
fmt.Println("shutdown:", err)
}
fmt.Println("--- server log ---")
for _, line := range logLines {
fmt.Println(line)
}
}
Output:
GET /v1/items/kb-01 -> 401 {"error":"unauthorized"}
GET /v1/items/kb-01 -> 200 {"sku":"kb-01","name":"Keyboard","stock":4}
GET /v1/items/zz-99 -> 404 {"error":"no such item"}
PUT /v1/items/kb-01 -> 400 {"error":"json: unknown field \"colour\""}
PUT /v1/items/kb-01 -> 200 {"sku":"kb-01","name":"Keyboard","stock":9}
GET /v1/boom -> 500 {"error":"internal"}
--- server log ---
req-001 GET /v1/items/kb-01 401 24B
req-002 GET /v1/items/kb-01 200 43B
req-003 GET /v1/items/zz-99 404 24B
req-004 PUT /v1/items/kb-01 400 42B
req-005 PUT /v1/items/kb-01 200 43B
req-006 panic recovered: simulated handler failure
req-006 GET /v1/boom 500 20B
The middleware order is the design. requestID is outermost, so even the 401 carries req-001 in its response header and in the log. logging sits outside recoverPanic, which is why req-006 produced a log line at all -- the panic was converted to a 500 below it, so as far as logging is concerned the handler returned normally. And requireToken is innermost, so unauthenticated requests are recorded and counted rather than dropped silently. Reverse any two of those and you lose a property: auth outermost means no request id on rejections, recovery outermost means a panicking handler produces no access-log entry at all.
statusWriter is how the log line knows 43B and 401. A ResponseWriter is write-only -- there is no w.Status() -- so capturing the outcome means wrapping it. The embedded interface forwards Header() untouched, and only the two methods that carry information are overridden. The cost of this trick is worth knowing: because statusWriter is a new type, it satisfies http.Flusher, http.Hijacker and io.ReaderFrom only if you forward them explicitly, so streaming or WebSocket handlers underneath this middleware will silently lose those capabilities unless you add the pass-throughs.
Three defensive details in the handlers are worth copying verbatim. DisallowUnknownFields turned "colour" into a 400 with a message naming the offending field, instead of accepting the payload and quietly discarding a value the client believed it had set. http.MaxBytesReader caps the body at 64 KB, because without it a client can stream gigabytes into Decode and the server will faithfully allocate them. And in.SKU = r.PathValue("sku") overwrites whatever the body claimed, so a PUT /v1/items/kb-01 cannot modify ms-02 by lying in its payload.
The auth check itself is deliberately small and deliberately careful. strings.CutPrefix distinguishes a missing header from a malformed one, subtle.ConstantTimeCompare avoids leaking the token's prefix through response timing, and the WWW-Authenticate header tells a well-behaved client what scheme to use. What it is not is a real authentication system -- a shared bearer token has no expiry, no scopes and no revocation. The point is the shape: one middleware, applied once, in front of everything, rather than an if at the top of every handler where the one you forget is the one that matters.
Common Mistakes
- Not closing
resp.Body. Every unclosed response leaks a connection and its reader goroutine.defer resp.Body.Close()goes on the line after the error check, and it applies even when you do not want the body. - Treating a 500 as an error from
Do.c.Doreturnsnilfor any response the server actually sent. Checkingerrwithout checkingresp.StatusCodemeans happily parsing an error page as your payload. - Using
http.Getorhttp.DefaultClientin a service. They have no timeout whatsoever, so one unresponsive dependency can pin your goroutines indefinitely. - Creating a client or transport per request. Each new
Transportis a fresh connection pool, so nothing is ever reused and every call pays a full TCP and TLS handshake. - Calling
http.ListenAndServein production. It leaves every timeout unset, so a client that opens a socket and sends nothing holds a connection for as long as it likes. - Writing a header after
WriteHeader. The header map is frozen at that point; the change is silently dropped. Set everything before the status. - Forgetting to
returnafter an error response. Execution continues, the handler writes a second status, and the server logs "superfluous response.WriteHeader call" while the client keeps the first one. - Reading
r.Bodywithout a size limit.io.ReadAll(r.Body)will allocate whatever the client chooses to send. Wrap it inhttp.MaxBytesReader. - Sharing mutable state between handlers without a lock. Handlers run concurrently in separate goroutines; a plain
mapwritten by two requests at once crashes the process with a concurrent map write. - Storing per-request data in a handler struct field. The struct is shared by every request; only
r.Context()and local variables are per-request. - Assuming
Shutdowncancels handler contexts. It waits for them. A handler in a thirty-second loop keeps the process alive for thirty seconds unless you give it a cancellable context of its own.
Best Practices
- Build an
&http.Server{}with all four timeouts set, run it withServeor its ownListenAndServe, and treathttp.ErrServerClosedas success. - Register routes with method-scoped Go 1.22 patterns (
"GET /v1/items/{sku}") so the mux rejects wrong verbs for you with a 405. - Express every cross-cutting concern as
func(http.Handler) http.Handlerand compose them in one place, so the order is visible in a single line. - Put authentication in front of the mux, not inside handlers, and cap every request body with
http.MaxBytesReader. - Bind to
127.0.0.1unless the service is genuinely meant to be reachable from other machines. - Use
json.NewDecoderwithDisallowUnknownFieldsfor request bodies, and let the URL rather than the payload decide which resource is being addressed. - Keep one
*http.Clientper outbound dependency, give each call its own context deadline, and drain plus close every body. - Test handlers with
httptest.NewRecorderand clients againsthttptest.NewServer, so the suite needs no fixed ports and no network.
Practice Exercises
- Register
/files/{path...},/files/{name}and/files/{$}on one mux and write a client that probes/files/,/files/aand/files/a/b/c, printing which pattern served each. Explain the precedence you observe. - Write a
timeoutmiddleware that gives every handler a 100ms context and returns 503 if the handler has not responded in time. Prove with a slow handler that the client sees 503, and explain why the handler's goroutine may still be running afterwards. - Test the JSON API from this lesson with
httptest.NewRecorder: assert the 401 without a token, the 200 with one, and the exactX-Request-Idheader. Then add anhttptest.NewServertest that exercises the same routes through a real client. - Add graceful shutdown driven by
os/signal: on SIGINT, stop accepting, cancel a server-wide context that handlers select on, and wait up to five seconds for in-flight requests. Show that a request already in progress completes and a new one is refused.