net/http: Server, Client, 1.22 Routing, Path & Query Params
"Go 1.22 brings two enhancements to the net/http package’s router: method matching and wildcards. These features let you express common routes as patterns instead of Go code." — Jonathan Amsterdam, "Routing Enhancements for Go 1.22", The Go Blog, 13 February 2024
Summary: net/http is a production HTTP server and client in the standard library: a Handler interface, a ServeMux router that matches hosts (always has) and, since Go 1.22, methods and path wildcards, an http.Server whose four timeouts you must set yourself, and an http.Client on top of a pooled, keep-alive, HTTP/2-capable Transport that you must create once and whose response bodies you must close. Focus: Handler/HandlerFunc/ServeMux, Go 1.22 patterns (method, host, {name}, {name...}, {$}), precedence and conflicts, r.PathValue and Request.Pattern, query and form parsing (URL.Query, ParseForm, FormValue precedence), body limits (http.MaxBytesReader), ResponseWriter rules (Header().Set before WriteHeader), http.Error and status codes, JSON helpers and streaming, content negotiation, static files (FileServerFS, ServeFileFS, embed, StripPrefix), cookies and redirects, server timeouts, TimeoutHandler, graceful shutdown, ResponseController, Flusher, SSE, Hijacker, ErrAbortHandler, the client's Transport, connection pooling, timeouts, NewRequestWithContext, closing and draining bodies, httptest, CrossOriginProtection, and when chi, gin or echo are worth a dependency. Learning goal: Write a Go HTTP service with only the standard library that routes by method and path, validates every input, answers with the right status code, cannot be held open by slow clients, shuts down without dropping requests, and calls other services through one shared client that reuses connections and never waits longer than its caller.
This page owns the net/http server and client as you use them every day. It does not re-teach its neighbours: cancellation, deadlines and r.Context() in depth are in context; middleware chaining (logging, recover, CORS, compression, rate limiting) is in Middlewares; a full layered CRUD service with validation, repositories and Swagger is in A REST API in Go; struct tags and encoding/json details are in JSON, XML & Encoder/Decoder; TLS, HTTP/2 tuning and mTLS are in HTTP/2, HTTPS, TLS & mTLS in Go; signals and process lifetime are in OS Processes, Signals & Graceful Shutdown; httptest as a testing tool is covered more broadly in Testing & Benchmarking. The protocol itself (HTTP/1.1 vs 2 vs 3, keep-alive on the wire) is in HTTP Evolution, resource and status-code design in REST API Design, the choice of timeout values in Timeouts, Retries & Jitter, long-lived connections in Real-Time Communication, and sockets and ports in Ports, Sockets & Connections.
Facts below were checked against the Go 1.27 standard-library source on go.dev (net/http server.go, client.go, transport.go, request.go, response.go, pattern.go, routing_tree.go, fs.go, responsecontroller.go, csrf.go, httptest, encoding/json/stream.go), the Go 1.6, 1.7, 1.8, 1.16, 1.19, 1.20 and 1.22 to 1.27 release notes, the Go blog post on routing, Filippo Valsorda's 2016 Cloudflare guide to net/http timeouts, Alex Edwards' router comparison (last updated May 2025), RFC 9110, RFC 6265, the WHATWG Server-Sent Events specification and the chi, gin and echo READMEs. Snippets declare go 1.24 (they use t.Context() and range-over-int) and have no third-party dependencies. They were compiled, vetted and tested with -race on Go 1.27.4 (macOS); the status codes and connection counts quoted from them are what that run printed. APIs newer than Go 1.24 (http.CrossOriginProtection from 1.25, Transport.NewClientConn from 1.26, Server.MaxHeaderValueCount and httptest.NewTestServer from 1.27) are shown in fenced blocks only, because go vet rejects them in a go 1.24 module ("requires go1.25 or later").
Page map
| If you are looking for | Go to |
|---|---|
| The tables you can memorise in one minute | Everything in one minute |
| Why a standard-library server is enough | Why it exists |
| Versions: 1.0 to 1.27 | Where it comes from |
| A before/after service | Go |
Handler, HandlerFunc, ServeMux | Handlers and the mux |
Method, host, {id}, {path...}, {$} | Go 1.22 routing patterns |
| Which pattern wins, conflicts, 405 | Precedence rules |
r.PathValue, Request.Pattern | Path parameters |
URL.Query, ParseForm, FormValue | Query and form parameters |
http.MaxBytesReader, 413 | Request body limits |
Header().Set, WriteHeader, http.Error | Writing the response |
| 200 vs 201 vs 204 vs 400 vs 422 | Status codes |
Decode/Encode, NDJSON, Accept | JSON helpers and content negotiation |
FileServerFS, ServeFileFS, embed | Static files |
SetCookie, Redirect, 303/307/308 | Cookies and redirects |
ReadHeaderTimeout and friends | Server timeouts |
http.TimeoutHandler, ErrAbortHandler | Handler budgets and aborts |
Shutdown, BaseContext, ErrServerClosed | Graceful shutdown |
ResponseController, Flusher, SSE, Hijacker | Streaming and connection control |
http.Client, Transport, pooling | The client and its Transport |
Client.Timeout, NewRequestWithContext | Client timeouts |
| Closing and draining bodies | Response bodies |
http.DefaultClient and http.Get | DefaultClient pitfalls |
httptest.NewRecorder, NewServer | Testing with httptest |
| CSRF protection in the stdlib | CrossOriginProtection |
| ServeMux vs chi, gin, echo | Routers and frameworks |
| Accept loop, conn goroutines, routing tree | Mechanics |
| The common bugs and their fixes | Solving the classic problems |
| What to use when | Choosing |
| Monolith to distributed system | In architecture |
| Reproduce it on your machine | Lab |
Laravel routes, Request, Http:: facade | For PHP/Laravel developers |
Everything in one minute
The server side in one table. Each row is unpacked in the concept catalogue.
| Piece | What it is | Plain words | Since |
|---|---|---|---|
http.Handler | ServeHTTP(ResponseWriter, *Request) | "Something that answers a request" | 1.0 |
http.HandlerFunc | Function type with a ServeHTTP method | "Use a plain function as a handler" | 1.0 |
http.ServeMux | Router: pattern → handler | "Pick the handler for this method and path" | 1.0 (hosts too); methods and wildcards 1.22 |
http.Server | Listener + connection loop + timeouts | "The process that accepts connections" | 1.0; Shutdown 1.8 |
ListenAndServe | Listen on TCP, then Serve | "Start; returns only on error" | 1.0 |
r.PathValue("id") | Value of a wildcard | "What {id} matched" | 1.22 |
r.URL.Query() | Parsed query string (url.Values) | "?page=2&tag=a&tag=b" | 1.0 |
http.MaxBytesReader | Bounded Request.Body | "Refuse bodies over N bytes" | 1.0; MaxBytesError 1.19 |
http.ResponseController | Flush, deadlines, hijack per request | "Extra controls on this response" | 1.20 |
Request.Pattern | The pattern that matched | "Which route served this" | 1.23 |
http.CrossOriginProtection | Fetch-metadata CSRF check | "Reject cross-site POSTs" | 1.25 |
Go 1.22 pattern syntax. The whole grammar is [METHOD ][HOST]/[PATH]; this one-line summary of Go 1.22 routing patterns (method, wildcards {id}, {path...}, {$}) covers what you write every day.
| Pattern | Matches | Does not match | PathValue |
|---|---|---|---|
/posts/ | /posts/, /posts/7, /posts/7/comments, any method | /posts (redirected to /posts/) | none |
GET /posts/{id} | GET or HEAD /posts/7 | /posts/7/comments, DELETE /posts/7 (405) | id = 7 |
GET /posts/latest | Exactly that path; beats /posts/{id} | /posts/latest/x | none |
/files/{path...} | /files/a/b/c.txt | nothing below /files/ is excluded | path = a/b/c.txt |
GET /{$} | Only / | /anything | none |
api.example.test/v1/ | Host api.example.test only | other hosts | none |
POST /users/{uid}/posts/{id} | POST /users/9/posts/42 | GET of the same path | uid, id |
The client side in one table.
| Knob | Default | What goes wrong at the default | Set it to |
|---|---|---|---|
http.Client.Timeout | 0 (none) | A hung upstream hangs your goroutine forever | A backstop, e.g. 10 s |
NewRequestWithContext(ctx, ...) | http.NewRequest uses context.Background() | Caller's deadline and disconnect ignored | Always the caller's ctx |
Transport.MaxIdleConnsPerHost | 2 (DefaultMaxIdleConnsPerHost) | Busy upstream: connections churn, TIME_WAIT piles up | Peak concurrency to that host |
Transport.MaxIdleConns | 100 in DefaultTransport | Fine for most; 0 means unlimited | Sum over hosts |
Transport.IdleConnTimeout | 90 s in DefaultTransport | Longer than the load balancer's idle timeout: stale conns | Below the upstream's idle timeout |
Transport.ResponseHeaderTimeout | 0 (none) | Server accepts, never answers | A few seconds |
resp.Body.Close() | Your job | Connection never returns to the pool | defer resp.Body.Close() after the error check |
The status codes a handler writes most. Constants live in net/http (http.StatusCreated and so on).
| Code | Constant | When |
|---|---|---|
| 200 | StatusOK | Read succeeded, body follows |
| 201 | StatusCreated | Created; add Location |
| 204 | StatusNoContent | Success, no body (DELETE, PUT without echo) |
| 303 | StatusSeeOther | After a form POST: "now GET this page" |
| 307 / 308 | StatusTemporaryRedirect / StatusPermanentRedirect | Redirect that keeps method and body |
| 400 | StatusBadRequest | Malformed syntax: bad JSON, non-integer id |
| 404 | StatusNotFound | No such resource or route |
| 405 | StatusMethodNotAllowed | Path exists, method does not; Allow header (ServeMux does it) |
| 413 | StatusRequestEntityTooLarge | Body over the limit |
| 415 | StatusUnsupportedMediaType | Wrong Content-Type |
| 422 | StatusUnprocessableEntity | Well-formed but invalid (empty name) |
| 502 / 504 | StatusBadGateway / StatusGatewayTimeout | Upstream failed / too slow |
| 503 | StatusServiceUnavailable | Overloaded, shutting down, or TimeoutHandler fired |
Why it exists
Most languages need a framework before they can serve HTTP in production; PHP needs a web server and FPM in front of it. Go ships the whole stack: a concurrent server that starts one goroutine per connection, a router, a client with connection pooling, TLS, HTTP/2, cookies, multipart forms and test helpers. Since Go 1.22 the router understands methods and path parameters, which removed the main reason people pulled in a third-party router. The price is that the defaults are tuned for compatibility, not for the open internet: no server timeouts, no client timeout, a per-host idle pool of two, and bodies you must close yourself. As Filippo Valsorda wrote in the Cloudflare guide, "timeouts are amongst the easiest and most subtle things to get wrong".
| Framework-first (Laravel, Express, Spring) | net/http |
|---|---|
| Router, request, response, client are framework objects | Plain interfaces any library can implement (http.Handler, http.RoundTripper) |
| Middleware has a framework signature | Middleware is func(http.Handler) http.Handler |
| Server process is separate (nginx + FPM) | The binary is the server |
| Safe-ish defaults hidden in config | Every limit explicit in your code; zero means "no limit" |
| Upgrades follow the framework | Go 1 compatibility promise; behaviour changes behind GODEBUG |
| Convenience: validation, binding, sessions | You write or pick small helpers (jsonio below) |
An everyday picture. A post office. The building with its doors is the http.Server; the doors close at night (Shutdown) but the clerks finish serving whoever is already at the counter. The sorting table is the ServeMux: it reads the method and the address on each envelope and drops it in the most specific pigeonhole ("Main Street 7" before "Main Street, any number"). A clerk is a Handler. The rules on the wall ("no parcels over 20 kg", "if you stand at the counter without speaking for five minutes you must leave") are MaxBytesReader and the timeouts. The post office's own van that drives to other offices is the http.Client; the van is kept and reused, not bought for every letter (Transport pooling), and the driver must unload the van before it can be used again (resp.Body.Close()).
Three common misunderstandings, up front
- "
http.ListenAndServe(":8080", mux)is production-ready." It builds anhttp.Serverwith every timeout at zero, so a client that sends headers one byte a minute holds a goroutine and a file descriptor forever. Build anhttp.Serverand set the timeouts. - "I closed the response body, so I am done." Closing is required, but you also have to check the status code (a 500 still has a body and
err == nil) and bound how much you read. - "Since Go 1.22 I never need a router library." For method, host and path wildcards, yes. For regex segments, route groups with their own middleware, or custom 405 pages, chi and friends still help (see Routers and frameworks).
Where it comes from
net/http was in Go 1.0 (March 2012) with Handler, HandlerFunc, ServeMux, Server, Client and Transport in roughly their current shape. Go 1.6 (2016) turned on HTTP/2 automatically: "Go clients and servers will automatically use HTTP/2 as appropriate when using HTTPS." Go 1.7 added Request.Context and Transport.IdleConnTimeout. Go 1.8 added graceful shutdown ("The HTTP Server now has support for graceful shutdown using the new Server.Shutdown method"), ReadHeaderTimeout and IdleTimeout. Go 1.16 added embed, which together with http.FS made single-binary web apps easy. Go 1.19 made MaxBytesReader return the typed *http.MaxBytesError. Go 1.20 added http.ResponseController, described as "a clearer, more discoverable way" to reach per-request features than optional interfaces like Flusher.
The routing change came in Go 1.22 (February 2024): methods and wildcards in ServeMux patterns (host-specific patterns such as example.test/ already existed, and the pre-1.22 matcher already gave them precedence), Request.PathValue and SetPathValue, and ServeFileFS/FileServerFS. The old matcher is still there behind GODEBUG=httpmuxgo121=1, and it is the default only for modules whose go.mod says a version before 1.22. Go 1.23 added Request.Pattern, Request.CookiesNamed, ParseCookie/ParseSetCookie, Cookie.Partitioned, and httptest.NewRequestWithContext. Go 1.24 added Server.Protocols/Transport.Protocols and unencrypted HTTP/2. Go 1.25 added http.CrossOriginProtection. Go 1.26 changed trailing-slash redirects: "ServeMux trailing slash redirects now use HTTP status 307 (Temporary Redirect) instead of 301 (Moved Permanently)." Go 1.27 made closing a body drain it: "HTTP/1 Response.Body now automatically drains any unread content upon being closed, up to a conservative limit, to allow better connection reuse."
1 Go 1.0 (2012) Handler, ServeMux (prefix patterns), Server, Client, Transport
2 Go 1.6 (2016) HTTP/2 on by default over TLS, server and client
3 Go 1.7 (2016) Request.Context, IdleConnTimeout, httptrace
4 Go 1.8 (2017) Server.Shutdown, ReadHeaderTimeout, IdleTimeout
5 Go 1.16 (2021) embed + http.FS
6 Go 1.19 (2022) *MaxBytesError
7 Go 1.20 (2023) ResponseController (Flush, SetReadDeadline, SetWriteDeadline, Hijack); Go 1.21 adds EnableFullDuplex
8 Go 1.22 (2024) methods, {name}, {name...}, {$} (hosts predate it); PathValue; ServeFileFS
9 Go 1.23 (2024) Request.Pattern, cookie parsing helpers
10 Go 1.24 (2025) Server.Protocols, Transport.Protocols, unencrypted HTTP/2
11 Go 1.25 (2025) CrossOriginProtection
12 Go 1.26 (2026) 307 for trailing-slash redirects, Transport.NewClientConn
13 Go 1.27 (2026) Body.Close drains, MaxHeaderValueCount, httptest.NewTestServerGo
Before
A service that works on a quiet day: routes registered on the global DefaultServeMux, a "/users/" prefix parsed with strings.TrimPrefix, no method check, http.ListenAndServe with no timeouts, and an outgoing call through http.Get that ignores the status code and reads an unbounded body.
// Package before shows a net/http service that works on a quiet day:
// the default mux, a prefix route parsed by hand, no method check,
// no server timeouts and the shared http.DefaultClient.
package before
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
)
// Register adds the routes to mux. Production code used http.HandleFunc,
// which registers on the global http.DefaultServeMux.
func Register(mux *http.ServeMux) {
// "/users/" matches every path below /users/ and every method.
mux.HandleFunc("/users/", func(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/users/") // "7", "7/orders", ""
if id == "" {
w.WriteHeader(http.StatusNotFound)
return
}
// No method check: DELETE /users/7 also returns the user.
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"id":%q}`, id)
})
}
// Run starts the server with no ReadHeaderTimeout, ReadTimeout,
// WriteTimeout or IdleTimeout: a slow client can hold a connection forever.
func Run(addr string) error {
Register(http.DefaultServeMux)
return http.ListenAndServe(addr, nil)
}
// Profile is what the upstream returns.
type Profile struct {
Name string `json:"name"`
}
// FetchProfile uses http.Get: http.DefaultClient has no timeout, the
// request has no context, and a non-2xx status is decoded as if it were data.
func FetchProfile(url string) (Profile, error) {
var p Profile
resp, err := http.Get(url)
if err != nil {
return p, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body) // unbounded read
if err != nil {
return p, err
}
err = json.Unmarshal(body, &p)
return p, err
}The test proves the two design bugs: DELETE /users/7 returns the user, /users/7/orders is read as the id 7/orders, and a 500 from the upstream is decoded as data.
package before
import (
"net/http"
"net/http/httptest"
"testing"
)
func TestPrefixRouteAcceptsAnyMethodAndAnyDepth(t *testing.T) {
mux := http.NewServeMux()
Register(mux)
cases := []struct {
method, path, body string
}{
{http.MethodGet, "/users/7", `{"id":"7"}`},
{http.MethodDelete, "/users/7", `{"id":"7"}`}, // should be 405 or a delete
{http.MethodGet, "/users/7/orders", `{"id":"7/orders"}`}, // a different resource
}
for _, c := range cases {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(c.method, c.path, nil))
if rec.Code != http.StatusOK || rec.Body.String() != c.body {
t.Fatalf("%s %s = %d %q", c.method, c.path, rec.Code, rec.Body.String())
}
}
}
func TestFetchProfileDecodesErrorBodies(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, `{"name":"from an error page"}`, http.StatusInternalServerError)
}))
defer up.Close()
p, err := FetchProfile(up.URL)
if err != nil || p.Name != "from an error page" {
t.Fatalf("got %+v, %v: a 500 was treated as data", p, err)
}
}After
The same service with its own ServeMux, one pattern per method and resource, the id parsed and validated from r.PathValue("id"), strict JSON helpers, explicit status codes, and the upstream call made through one shared client with a 300 ms budget derived from r.Context(). Timeouts and shutdown live in the server package.
// Package after is the before service rebuilt: its own ServeMux with
// method + wildcard patterns, strict JSON helpers, explicit status codes,
// server timeouts and graceful shutdown (in package server), and a
// context-bound client for the upstream call.
package after
import (
"context"
"errors"
"net/http"
"strconv"
"sync"
"time"
"academy/http-server-client/client"
"academy/http-server-client/jsonio"
)
// User is the resource.
type User struct {
ID int64 `json:"id"`
Name string `json:"name"`
}
// App holds dependencies; handlers are methods, not globals.
type App struct {
mu sync.Mutex
users map[int64]User
next int64
http *http.Client
review string // upstream base URL
}
// New returns an App that calls the review service at reviewURL.
func New(reviewURL string) *App {
return &App{users: map[int64]User{}, next: 1, http: client.New(), review: reviewURL}
}
// Routes is the whole API surface, readable in one place.
func (a *App) Routes() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("POST /users", a.createUser)
mux.HandleFunc("GET /users/{id}", a.getUser)
mux.HandleFunc("DELETE /users/{id}", a.deleteUser)
mux.HandleFunc("GET /users/{id}/reviews", a.userReviews)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
})
return mux
}
func pathID(r *http.Request) (int64, bool) {
id, err := strconv.ParseInt(r.PathValue("id"), 10, 64)
return id, err == nil && id > 0
}
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
var in struct {
Name string `json:"name"`
}
if err := jsonio.Decode(w, r, &in, 16<<10); err != nil {
jsonio.Fail(w, err)
return
}
if in.Name == "" {
jsonio.Problem(w, http.StatusUnprocessableEntity, "name is required")
return
}
a.mu.Lock()
u := User{ID: a.next, Name: in.Name}
a.users[u.ID] = u
a.next++
a.mu.Unlock()
w.Header().Set("Location", "/users/"+strconv.FormatInt(u.ID, 10))
_ = jsonio.Write(w, http.StatusCreated, u)
}
func (a *App) getUser(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
jsonio.Problem(w, http.StatusBadRequest, "id must be a positive integer")
return
}
a.mu.Lock()
u, found := a.users[id]
a.mu.Unlock()
if !found {
jsonio.Problem(w, http.StatusNotFound, "no such user")
return
}
_ = jsonio.Write(w, http.StatusOK, u)
}
func (a *App) deleteUser(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
jsonio.Problem(w, http.StatusBadRequest, "id must be a positive integer")
return
}
a.mu.Lock()
delete(a.users, id) // idempotent: deleting twice is still 204
a.mu.Unlock()
w.WriteHeader(http.StatusNoContent)
}
func (a *App) userReviews(w http.ResponseWriter, r *http.Request) {
id, ok := pathID(r)
if !ok {
jsonio.Problem(w, http.StatusBadRequest, "id must be a positive integer")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 300*time.Millisecond)
defer cancel()
var reviews []string
err := client.GetJSON(ctx, a.http, a.review+"/reviews?user="+strconv.FormatInt(id, 10), &reviews)
var se *client.StatusError
switch {
case err == nil:
_ = jsonio.Write(w, http.StatusOK, reviews)
case errors.Is(err, context.DeadlineExceeded):
jsonio.Problem(w, http.StatusGatewayTimeout, "review service too slow")
case errors.As(err, &se):
jsonio.Problem(w, http.StatusBadGateway, "review service failed")
case errors.Is(err, context.Canceled):
return // client went away; nobody reads the answer
default:
jsonio.Problem(w, http.StatusBadGateway, "review service unreachable")
}
}The test walks the status codes (201, 422, 400, 200, 404, 405, 204) and maps a slow, a failing and a healthy upstream to 504, 502 and 200.
package after
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func do(h http.Handler, method, path, body string) *httptest.ResponseRecorder {
var r *http.Request
if body != "" {
r = httptest.NewRequest(method, path, strings.NewReader(body))
r.Header.Set("Content-Type", "application/json")
} else {
r = httptest.NewRequest(method, path, nil)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, r)
return rec
}
func TestCRUDStatusCodes(t *testing.T) {
h := New("http://unused.invalid").Routes()
steps := []struct {
method, path, body string
code int
}{
{"POST", "/users", `{"name":"ana"}`, 201},
{"POST", "/users", `{"name":""}`, 422},
{"POST", "/users", `{"nmae":"x"}`, 400},
{"GET", "/users/1", "", 200},
{"GET", "/users/abc", "", 400},
{"GET", "/users/99", "", 404},
{"PUT", "/users/1", "", 405},
{"DELETE", "/users/1", "", 204},
{"DELETE", "/users/1", "", 204},
{"GET", "/users/1", "", 404},
{"GET", "/users/1/orders", "", 404}, // not silently treated as id "1/orders"
}
for _, s := range steps {
if rec := do(h, s.method, s.path, s.body); rec.Code != s.code {
t.Errorf("%s %s = %d %s, want %d", s.method, s.path, rec.Code, rec.Body.String(), s.code)
}
}
}
func TestLocationHeaderOnCreate(t *testing.T) {
rec := do(New("http://unused.invalid").Routes(), "POST", "/users", `{"name":"ana"}`)
if rec.Header().Get("Location") != "/users/1" {
t.Fatalf("Location %q", rec.Header().Get("Location"))
}
}
func TestUpstreamFailuresMapToGatewayStatuses(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(time.Second):
case <-r.Context().Done():
}
}))
defer slow.Close()
broken := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
}))
defer broken.Close()
ok := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`["great pen"]`))
}))
defer ok.Close()
for url, want := range map[string]int{slow.URL: 504, broken.URL: 502, ok.URL: 200} {
if rec := do(New(url).Routes(), "GET", "/users/1/reviews", ""); rec.Code != want {
t.Errorf("%s: %d, want %d", url, rec.Code, want)
}
}
}The Go angle
Everything in net/http meets at two small interfaces: http.Handler on the server and http.RoundTripper on the client. A router is a Handler, middleware is a function from Handler to Handler, httptest.NewRecorder is a ResponseWriter, a retrying or tracing client is a RoundTripper that wraps another one. That is why chi, gorilla/mux, OpenTelemetry's otelhttp, Prometheus' promhttp and gRPC-gateway all plug into the same server. The other Go-specific trait is the goroutine-per-connection model: handler code is written as plain blocking code, and the scheduler multiplexes thousands of connections onto a few OS threads. The cost is that each blocked handler is a live goroutine, so every limit (body size, timeouts, upstream budgets) is also a memory limit.
The concept catalogue
Handlers, HandlerFunc and the ServeMux Must-know
In plain words: A handler is anything with a ServeHTTP(w, r) method. http.HandlerFunc(f) turns a plain function into one. A ServeMux is itself a handler that looks at the request and forwards it to the handler registered for the best-matching pattern.
Common misunderstanding: "http.HandleFunc is the normal way to register routes." It registers on the package-level http.DefaultServeMux, a global that any imported package can add routes to (net/http/pprof registers /debug/pprof/ there in its init). Create your own http.NewServeMux() and pass it to your http.Server; then nothing appears in your API that you did not put there.
Definition: type Handler interface { ServeHTTP(ResponseWriter, *Request) }. The doc is strict about the lifetime: "Returning signals that the request is finished; it is not valid to use the [ResponseWriter] or read from the [Request.Body] after or concurrently with the completion of the ServeHTTP call." type HandlerFunc func(ResponseWriter, *Request) is "an adapter to allow the use of ordinary functions as HTTP handlers". Server.Handler defaults to DefaultServeMux when nil. A panic in a handler is recovered by the server, logged with a stack trace, and the connection is closed (HTTP/1) or the stream reset (HTTP/2).
net/http server your ServeMux your handler
1 accept conn, go c.serve()
2 read request line + headers
3 srv.Handler.ServeHTTP(w, r) ──▶ match "GET /users/{id}"
4 r.Pattern, path values set ──▶ getUser(w, r)
5 w.Header().Set(...)
6 w.WriteHeader(200); w.Write(body)
7 finish response, keep-alive ◀────────────────────────────────── returnReal scenario: a JSON API with twenty routes on one mux; an admin mux mounted under /admin/ with its own auth middleware; a health-check handler that must answer even when the main mux is wrapped in heavy middleware; pprof accidentally exposed on the public port because a dependency imported net/http/pprof and the app used DefaultServeMux.
| Registration | Registers on | Use in production? |
|---|---|---|
http.HandleFunc(p, f) | http.DefaultServeMux (global) | No: hidden routes, shared global state |
http.Handle(p, h) | http.DefaultServeMux | No |
mux := http.NewServeMux(); mux.HandleFunc(p, f) | Your mux | Yes |
mux.Handle(p, http.HandlerFunc(f)) | Your mux | Yes (same as HandleFunc) |
mux.Handle("/admin/", http.StripPrefix("/admin", adminMux)) | Sub-mux under a prefix | Yes |
http.ListenAndServe(addr, nil) | Serves DefaultServeMux | No: no timeouts either |
Fix / how to use it: one NewServeMux per server, handlers as methods on a struct that holds the dependencies (App in the After snippet), and the mux wrapped in middleware once at the top (server.New(addr, logging(recoverer(mux)), ctx)); middleware itself is in Middlewares.
Go 1.22 routing patterns: method, host, wildcards and {$} Must-know
In plain words: A pattern can start with a method (GET , POST ), may name a host, and its path can contain wildcards: {id} matches one segment, {path...} matches the rest of the path, and {$} means "the path ends here". A trailing slash still means "this whole subtree".
Common misunderstanding: "/ is the home page." Without {$}, the pattern / matches every path, so every typo URL renders your home page with a 200. Write GET /{$} for the home page. Another one: "GET /x only matches GET." It also matches HEAD; the blog: "As a special case, GET also matches HEAD; all the other methods match exactly."
Definition: the ServeMux doc: "In general, a pattern looks like [METHOD ][HOST]/[PATH]" and "If METHOD is present, it must be followed by at least one space or tab" (Go 1.23 relaxed this from exactly one space). Literal parts match case-sensitively. "Wildcards must be full path segments: they must be preceded by a slash and followed by either a slash or the end of the string", so /b_{bucket} is invalid and panics at registration. "Normally a wildcard matches only a single path segment, ending at the next literal slash (not %2F) in the request URL." "The special wildcard {$} matches only the end of the URL." Paths are unescaped segment by segment before matching, so /posts/a%2Fb matches /posts/{id} with id = a/b.
request pattern result (real test output, Go 1.27.4)
1 GET / GET /{$} 200 pattern="GET /{$}"
2 GET /nothing-here (no match) 404 page not found
3 GET /posts/42 GET /posts/{id} 200 id="42"
4 HEAD /posts/42 GET /posts/{id} 200 (GET covers HEAD)
5 GET /posts/a%2Fb GET /posts/{id} 200 id="a/b" (unescaped)
6 GET /files/a/b/c.txt GET /files/{path...} 200 path="a/b/c.txt"
7 GET /static GET /static/ 307 Location: /static/
8 POST api.example.test/version api.example.test/version 200 (host pattern, any method)Real scenario: a blog with GET /posts/{slug} and POST /posts; an object store with /b/{bucket}/o/{object...} (the example in the ServeMux doc); a multi-tenant app routing admin.example.test/ and api.example.test/ to different handlers in one process; a single-page app where GET /{$} serves index.html and GET /assets/ serves files.
| Element | Syntax | Rule | Invalid example |
|---|---|---|---|
| Method | GET /x | Space or tab after it; GET also matches HEAD | GET/x |
| Host | example.test/x | Matches that host only (port stripped) | n/a |
| Segment wildcard | {name} | Whole segment; name is a Go identifier | /b_{bucket}, /{1x} |
| Rest wildcard | {name...} | Only at the end | /{rest...}/x |
| End anchor | {$} | Only at the end; disables subtree match | /{$}/x |
| Trailing slash | /static/ | Anonymous rest wildcard: whole subtree | n/a |
| Same name twice | /{id}/{id} | Rejected | panics |
Fix / how to use it: the routing snippet registers every form above; its test is the table in the timeline.
// Package routing shows Go 1.22+ ServeMux patterns: methods, hosts,
// wildcards {name} and {name...}, the {$} anchor, the "most specific
// wins" precedence rule, Request.PathValue and Request.Pattern.
package routing
import (
"fmt"
"net/http"
)
// echo reports which pattern matched and what the wildcards captured.
func echo(names ...string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "pattern=%q", r.Pattern) // Request.Pattern: Go 1.23
for _, n := range names {
fmt.Fprintf(w, " %s=%q", n, r.PathValue(n))
}
}
}
// NewMux registers overlapping patterns on purpose. Registration order
// does not matter: the most specific pattern wins.
func NewMux() *http.ServeMux {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", echo()) // only "/"
mux.HandleFunc("GET /posts/{id}", echo("id")) // one segment
mux.HandleFunc("GET /posts/latest", echo()) // more specific than {id}
mux.HandleFunc("POST /posts", echo()) // same path family, other method
mux.HandleFunc("GET /users/{uid}/posts/{id}", echo("uid", "id"))
mux.HandleFunc("GET /files/{path...}", echo("path")) // rest of the path, slashes included
mux.HandleFunc("GET /static/", echo()) // trailing slash: a subtree
mux.HandleFunc("api.example.test/version", echo()) // host-specific, any method
return mux
}
// WithCatchAll adds a "/" handler for custom 404 pages. It matches every
// method and path, so requests that used to get 405 Method Not Allowed
// now reach it and get 404 instead.
func WithCatchAll() *http.ServeMux {
mux := NewMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "custom not found", http.StatusNotFound)
})
return mux
}
// Conflict registers two patterns where neither is more specific than the
// other. ServeMux panics at registration time, not at request time.
func Conflict() (err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("%v", r)
}
}()
mux := http.NewServeMux()
mux.HandleFunc("/posts/{id}", echo("id"))
mux.HandleFunc("/{resource}/latest", echo("resource"))
return nil
}Precedence rules and conflicts Must-know
In plain words: When several patterns match, the most specific one wins, and registration order never matters. "More specific" means it matches a strict subset of the requests the other one matches. If two patterns overlap and neither is more specific, registering the second one panics.
Common misunderstanding: "The longest pattern wins" (the pre-1.22 rule) or "the first registered wins" (gorilla/mux, flow). The blog explains why longest-wins fails: it "would select /posts/latest over /posts/{id}, but would choose /posts/{identifier} over both. That seems wrong: the wildcard name shouldn’t matter."
Definition: the doc: "If two or more patterns match a request, then the most specific pattern takes precedence. A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests". A method makes a pattern more specific (GET /posts/{id} beats /posts/{id}). One exception for compatibility: "if two patterns would otherwise conflict and one has a host while the other does not, then the pattern with the host takes precedence." A request whose path matches some pattern but whose method matches none gets 405 with an Allow header, which RFC 9110 requires: "An origin server MUST generate an Allow header field in a 405 (Method Not Allowed) response".
registered: /posts/ /posts/{id} GET /posts/{id} GET /posts/latest
1 GET /posts/latest all four match
2 /posts/{id} ⊂ /posts/ (one segment vs subtree)
3 GET /posts/{id} ⊂ /posts/{id} (method narrows)
4 GET /posts/latest ⊂ GET /posts/{id} (literal narrows)
5 winner: GET /posts/latest; r.Pattern == "GET /posts/latest"
conflict: /posts/{id} vs /{resource}/latest
6 both match /posts/latest; each matches something the other does not
7 second HandleFunc panics: "... But neither is more specific than the other."Real scenario: /users/me next to /users/{id} (works: me is more specific); GET /items/{id} and DELETE /items/{id} on separate handlers (works, and PUT gets 405); a catch-all / added for a custom 404 page, which silently turns every 405 into a 404 because / matches every method (the test TestCatchAllHides405 proves it; Alex Edwards lists it as a known limitation); a plugin registering /{tenant}/settings next to /billing/{id}, which panics at startup, the best time to find out.
| Pair | Request | Winner | Why |
|---|---|---|---|
/posts/latest vs /posts/{id} | /posts/latest | /posts/latest | Literal beats wildcard |
GET /posts/{id} vs /posts/{id} | GET /posts/7 | GET /posts/{id} | Method narrows |
/images/thumbnails/ vs /images/ | /images/thumbnails/a.png | /images/thumbnails/ | Longer subtree |
example.test/ vs / | host example.test | example.test/ | Host exception |
/posts/{id} vs /{resource}/latest | /posts/latest | none | Conflict: panic at registration |
GET / vs /index.html | GET /index.html | none | Conflict (example from the doc) |
GET /posts/{id} only | DELETE /posts/7 | none | 405, Allow: GET, HEAD |
Fix / how to use it: let the mux answer 404 and 405 itself; if you need a custom 404, wrap the mux and replace the body when the status is 404 rather than registering /. Run your route registration in a test (NewMux() in a test function) so conflicts fail CI, not the deploy.
package routing
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestPatterns(t *testing.T) {
mux := NewMux()
cases := []struct {
method, url string
code int
want string // substring of body, Allow or Location
}{
{"GET", "/", 200, `pattern="GET /{$}"`},
{"GET", "/nothing-here", 404, "404 page not found"}, // {$}: "/" no longer catches all
{"GET", "/posts/42", 200, `id="42"`},
{"GET", "/posts/latest", 200, `pattern="GET /posts/latest"`}, // more specific wins
{"HEAD", "/posts/42", 200, ""}, // GET also matches HEAD
{"DELETE", "/posts/42", 405, "GET, HEAD"}, // Allow header
{"GET", "/posts/a%2Fb", 200, `id="a/b"`}, // value is unescaped
{"GET", "/users/9/posts/42", 200, `uid="9" id="42"`},
{"GET", "/files/a/b/c.txt", 200, `path="a/b/c.txt"`},
{"GET", "/static", 307, "/static/"}, // trailing-slash redirect (307 since Go 1.26)
{"GET", "/posts/../posts/7", 307, "/posts/7"}, // path cleaning redirect
{"POST", "http://api.example.test/version", 200, `pattern="api.example.test/version"`},
{"GET", "http://other.example.test/version", 404, ""},
}
for _, c := range cases {
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(c.method, c.url, nil))
got := rec.Body.String() + "|" + rec.Header().Get("Allow") + "|" + rec.Header().Get("Location")
if rec.Code != c.code || !strings.Contains(got, c.want) {
t.Errorf("%s %s = %d %q, want %d containing %q", c.method, c.url, rec.Code, got, c.code, c.want)
}
}
}
func TestCatchAllHides405(t *testing.T) {
rec := httptest.NewRecorder()
WithCatchAll().ServeHTTP(rec, httptest.NewRequest(http.MethodDelete, "/posts/42", nil))
if rec.Code != http.StatusNotFound {
t.Fatalf("got %d: the catch-all should have swallowed the 405", rec.Code)
}
}
func TestConflictPanicsAtRegistration(t *testing.T) {
err := Conflict()
if err == nil || !strings.Contains(err.Error(), "neither is more specific") {
t.Fatalf("got %v", err)
}
}Path parameters: r.PathValue and Request.Pattern Must-know
In plain words: r.PathValue("id") returns the text the {id} wildcard matched, already unescaped. It is always a string; converting and validating it is your job. r.Pattern, the Request.Pattern (1.23) field, tells you which pattern matched, which is what you want as a metrics label.
Common misunderstanding: "PathValue returns an error if the name is wrong." It returns "" both when the wildcard is missing and when the request was not routed by a ServeMux at all, so a typo (r.PathValue("ID")) looks like an empty id. Another one: labelling metrics with r.URL.Path creates one time series per user id; label with r.Pattern.
Definition: "PathValue returns the value for the named path wildcard in the [ServeMux] pattern that matched the request. It returns the empty string if the request was not matched against a pattern or there is no such wildcard in the pattern." "The value is unescaped." SetPathValue lets other routers fill the same slot, so handlers stay portable. Request.Pattern "is the [ServeMux] pattern that matched the request. It is empty if the request was not matched against a pattern." It "is not set when GODEBUG=httpmuxgo121=1 is set."
1 GET /shops/7/products?page=2
2 mux matches "GET /shops/{shop}/products"; r.Pattern set; matches[0] = "7"
3 handler: shop := r.PathValue("shop") -> "7" (string)
4 strconv.ParseInt(shop, 10, 64) -> 7, nil
5 r.PathValue("shopId") -> "" (typo: no error)
6 metrics: http_requests_total{route="GET /shops/{shop}/products"} one series, not one per shopReal scenario: /orders/{id} where id must be a positive int64, so abc and -1 are 400; /files/{path...} where the value must be checked for .. before it touches a filesystem; to confine access use os.OpenRoot(dir) and root.FS() (Go 1.24), because os.DirFS does not stop a symlink inside the tree from pointing outside it; /users/{uid}/posts/{id} with two values; Prometheus and OpenTelemetry route labels from r.Pattern.
| Source of a parameter | API | Type | Missing value |
|---|---|---|---|
| Path wildcard | r.PathValue("id") | string, unescaped | "" |
| Query string | r.URL.Query().Get("page") | string | "" |
| Repeated query key | r.URL.Query()["tag"] | []string | nil |
| Form body | r.PostFormValue("name") | string | "" |
| Header | r.Header.Get("X-Request-Id") | string, canonical key | "" |
| Cookie | r.Cookie("session") | *http.Cookie, error | http.ErrNoCookie |
| JSON body | json.Decoder.Decode(&v) | your struct | zero values |
Fix / how to use it: parse once at the top of the handler into typed values and return 400 on failure, exactly as pathID in the After snippet and ShopProducts below do.
Query and form parameters: URL.Query, ParseForm, r.FormValue Must-know
In plain words: r.URL.Query() parses the query string into url.Values, a map[string][]string. r.FormValue("k") is a convenience that looks in the body form and the query and returns the first value, ignoring errors. r.ParseForm() does the parsing explicitly and returns the error.
Common misunderstanding: "FormValue reads the query string." It reads the url-encoded body first (for POST, PUT and PATCH), then the query, then a multipart body, and it swallows every parse error, including "body too large". The doc lists the order: "1. application/x-www-form-urlencoded form body (POST, PUT, PATCH only) 2. query parameters (always) 3. multipart/form-data form body (always)" and says it "ignores any errors returned by these functions". Also, r.URL.Query() re-parses RawQuery on every call; call it once.
Definition: ParseForm "populates r.Form and r.PostForm". For POST, PUT and PATCH "it also reads the request body, parses it as a form and puts the results into both r.PostForm and r.Form. Request body parameters take precedence over URL query string values in r.Form." Without a MaxBytesReader, "the size is capped at 10MB". ParseMultipartForm(maxMemory) keeps up to maxMemory bytes of file parts in memory and spills the rest to temporary files. Since Go 1.17 semicolons are no longer query separators; http.AllowQuerySemicolons restores the old behaviour, with the doc's warning that the mismatch with proxies "can lead to security issues".
POST /form?name=from-query body: name=from-body (application/x-www-form-urlencoded)
1 r.ParseForm()
2 r.PostForm = {name: [from-body]}
3 r.Form = {name: [from-body from-query]} body first, then query
4 r.FormValue("name") -> "from-body"
5 r.PostFormValue("name") -> "from-body"
6 r.URL.Query().Get("name") -> "from-query"Real scenario: a product list with ?page=3&per_page=50&sort=price&tag=red&tag=xl; an HTML login form posted as url-encoded; a search box where ?q=a+b must decode to a b (+ is a space in query strings, %2B is a plus); an API that receives an unexpected ?page=abc and must say 400, not silently use page 1.
| API | Reads | Errors | Repeated keys |
|---|---|---|---|
r.URL.Query() | Query only, parsed per call | Malformed pairs dropped silently | q["tag"] |
r.URL.Query().Get(k) | First query value | none | First only |
r.ParseForm() | Query + url-encoded body (POST/PUT/PATCH) | Returned | r.Form[k] |
r.FormValue(k) | Body, then query, then multipart | Ignored | First only |
r.PostFormValue(k) | Body only | Ignored | First only |
r.ParseMultipartForm(n) | multipart/form-data, files to temp files past n | Returned | r.MultipartForm |
r.FormFile(k) | One uploaded file | Returned (ErrMissingFile) | First file |
Fix / how to use it: validate into a typed struct with a whitelist for sort columns (never interpolate a query parameter into SQL), collect all errors with errors.Join so the client fixes them in one round trip, and call ParseForm yourself when you need to know it failed.
// Package params reads path and query parameters and form values:
// r.PathValue, r.URL.Query, r.FormValue, ParseForm and validation.
package params
import (
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
)
// ListQuery is the validated form of ?page=2&per_page=50&sort=-created&tag=a&tag=b.
type ListQuery struct {
Page int
PerPage int
Sort string
Tags []string
}
var sortable = []string{"created", "-created", "price", "-price"}
// ParseList validates query parameters. url.Values is a map[string][]string:
// Get returns the first value, the slice holds repeated keys.
func ParseList(q url.Values) (ListQuery, error) {
lq := ListQuery{Page: 1, PerPage: 20, Sort: "-created", Tags: q["tag"]}
var errs []error
if v := q.Get("page"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
errs = append(errs, fmt.Errorf("page must be a positive integer, got %q", v))
}
lq.Page = n
}
if v := q.Get("per_page"); v != "" {
n, err := strconv.Atoi(v)
if err != nil || n < 1 || n > 100 {
errs = append(errs, fmt.Errorf("per_page must be 1..100, got %q", v))
}
lq.PerPage = n
}
if v := q.Get("sort"); v != "" {
if !slices.Contains(sortable, v) {
errs = append(errs, fmt.Errorf("sort must be one of %v", sortable))
}
lq.Sort = v
}
return lq, errors.Join(errs...)
}
// ShopProducts handles GET /shops/{shop}/products?page=..&tag=..
func ShopProducts(w http.ResponseWriter, r *http.Request) {
shop := r.PathValue("shop")
id, err := strconv.ParseInt(shop, 10, 64)
if err != nil || id <= 0 {
http.Error(w, "shop must be a positive integer", http.StatusBadRequest)
return
}
lq, err := ParseList(r.URL.Query()) // parses RawQuery on every call: call once
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "shop=%d page=%d per_page=%d sort=%s tags=%v", id, lq.Page, lq.PerPage, lq.Sort, lq.Tags)
}
// Form shows where FormValue and PostFormValue look. FormValue ignores
// parse errors, so the handler calls ParseForm first and checks it.
func Form(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, 4<<10)
if err := r.ParseForm(); err != nil {
var maxErr *http.MaxBytesError
if errors.As(err, &maxErr) {
http.Error(w, "form too large", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "bad form", http.StatusBadRequest)
return
}
fmt.Fprintf(w, "FormValue=%q PostFormValue=%q Query=%q all=%q",
r.FormValue("name"), r.PostFormValue("name"), r.URL.Query().Get("name"), r.Form["name"])
}package params
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func mux() *http.ServeMux {
m := http.NewServeMux()
m.HandleFunc("GET /shops/{shop}/products", ShopProducts)
m.HandleFunc("POST /form", Form)
return m
}
func TestShopProducts(t *testing.T) {
cases := []struct {
url string
code int
want string
}{
{"/shops/7/products", 200, "shop=7 page=1 per_page=20 sort=-created tags=[]"},
{"/shops/7/products?page=3&per_page=50&sort=price&tag=red&tag=xl", 200, "page=3 per_page=50 sort=price tags=[red xl]"},
{"/shops/7/products?tag=a%20b", 200, "tags=[a b]"},
{"/shops/abc/products", 400, "shop must be"},
{"/shops/7/products?page=0&per_page=500", 400, "per_page must be 1..100"},
{"/shops/7/products?sort=drop+table", 400, "sort must be one of"},
}
for _, c := range cases {
rec := httptest.NewRecorder()
mux().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, c.url, nil))
if rec.Code != c.code || !strings.Contains(rec.Body.String(), c.want) {
t.Errorf("%s = %d %q", c.url, rec.Code, rec.Body.String())
}
}
}
func TestFormValuePrecedence(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/form?name=from-query", strings.NewReader("name=from-body"))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
mux().ServeHTTP(rec, r)
want := `FormValue="from-body" PostFormValue="from-body" Query="from-query" all=["from-body" "from-query"]`
if rec.Body.String() != want {
t.Fatalf("got %s", rec.Body.String())
}
}
func TestFormTooLarge(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/form", strings.NewReader("name="+strings.Repeat("x", 8<<10)))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
mux().ServeHTTP(rec, r)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("got %d %s", rec.Code, rec.Body.String())
}
}The sort whitelist matters because the value ends up in SQL. Bind values, whitelist identifiers:
-- table behind GET /shops/{shop}/products
CREATE TABLE products (
id bigint PRIMARY KEY,
shop_id bigint NOT NULL,
name text NOT NULL,
price integer NOT NULL,
tags text[] NOT NULL DEFAULT '{}',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX products_shop_created ON products (shop_id, created_at DESC);
-- page=3, per_page=50, sort=-created, tag=red: values are bound, ORDER BY comes from the whitelist
SELECT id, name, price
FROM products
WHERE shop_id = $1 AND tags @> $2::text[]
ORDER BY created_at DESC
LIMIT $3 OFFSET $4; -- $3 = 50, $4 = (3-1)*50; keyset pagination is in /database/paginationRequest body limits: http.MaxBytesReader Must-know
In plain words: r.Body is a stream straight from the socket, and nothing limits it unless you do; the r.Body limits you set are the only ones there are. Wrap it with http.MaxBytesReader(w, r.Body, n) before reading; reads past n bytes fail with *http.MaxBytesError and you answer 413.
Common misunderstanding: "MaxHeaderBytes limits the request size." It limits only the request line and headers ("It does not limit the size of the request body"). Another: "io.LimitReader does the same." It silently truncates, so a 2 MB JSON body becomes a syntax error at 1 MB instead of a clear 413, and it does not tell the server to close the connection.
Definition: "MaxBytesReader is similar to [io.LimitReader] but is intended for limiting the size of incoming request bodies. In contrast to io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a non-nil error of type [*MaxBytesError] for a Read beyond the limit, and closes the underlying reader when its Close method is called." Its purpose: "MaxBytesReader prevents clients from accidentally or maliciously sending a large request and wasting server resources. If possible, it tells the [ResponseWriter] to close the connection after the limit has been reached." The error text is fixed: http: request body too large ("Due to Hyrum's law, this text cannot be changed").
1 client: POST /upload Content-Length: 4096 (limit 1024)
2 handler: r.Body = http.MaxBytesReader(w, r.Body, 1024)
3 io.Copy(io.Discard, r.Body) reads 1024 bytes, then error *MaxBytesError{Limit: 1024}
4 handler: 413 "http: request body too large"
5 server: marks the connection to close after this response (rest of body not read)Real scenario: a JSON API that accepts 16 KB documents and must not buffer a 2 GB POST; image uploads capped at 10 MB with ParseMultipartForm; a webhook receiver exposed to the internet; a form handler where the implicit 10 MB cap of ParseForm is far too generous.
| Limit | Applies to | Default | Error |
|---|---|---|---|
Server.MaxHeaderBytes | Request line + headers | 1 MB (DefaultMaxHeaderBytes = 1 << 20) | 431 Request Header Fields Too Large |
http.MaxBytesReader | Request.Body | none | *MaxBytesError, you write 413 |
ParseForm implicit cap | url-encoded body | 10 MB | error from ParseForm |
ParseMultipartForm(maxMemory) | File parts in memory | your arg (FormValue uses 32 MB) | spills to temp files |
Server.ReadTimeout | Time to read the whole request | 0 (none) | connection closed |
Reverse proxy (nginx client_max_body_size) | Before Go sees it | 1m (nginx docs) | 413 from the proxy |
Fix / how to use it: a per-route limit, applied in the decode helper (16 KB in createUser) or in a middleware for whole route groups:
// Package limits puts bounds on a handler: a body size cap with
// http.MaxBytesReader, a whole-handler budget with http.TimeoutHandler,
// and an abort that the server does not log (http.ErrAbortHandler).
package limits
import (
"errors"
"io"
"net/http"
"time"
)
// Upload reads at most max bytes of body and reports how many it got.
func Upload(max int64) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
r.Body = http.MaxBytesReader(w, r.Body, max)
n, err := io.Copy(io.Discard, r.Body)
var maxErr *http.MaxBytesError
switch {
case errors.As(err, &maxErr):
// The server will also close the connection after this response.
http.Error(w, "http: request body too large", http.StatusRequestEntityTooLarge)
return
case err != nil:
http.Error(w, "read error", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusNoContent)
_ = n
}
}
// Slow simulates work that watches its context, as every handler should.
func Slow(d time.Duration) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(d):
_, _ = io.WriteString(w, "done")
case <-r.Context().Done(): // TimeoutHandler cancels this context
_, err := io.WriteString(w, "too late")
_ = err // http.ErrHandlerTimeout once TimeoutHandler has answered
}
}
}
// Budget wraps h so that the client gets 503 + msg after d.
// TimeoutHandler buffers h's output and does not support Flusher or Hijacker.
func Budget(h http.Handler, d time.Duration) http.Handler {
return http.TimeoutHandler(h, d, "request budget exhausted")
}
// Abort stops a response half-way: the client sees a broken response,
// and the server does not log a stack trace.
func Abort(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Length", "100")
_, _ = io.WriteString(w, "partial")
panic(http.ErrAbortHandler)
}package limits
import (
"bytes"
"io"
"log"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestUploadLimit(t *testing.T) {
h := Upload(1 << 10)
for size, want := range map[int]int{512: 204, 4 << 10: 413} {
rec := httptest.NewRecorder()
h(rec, httptest.NewRequest(http.MethodPost, "/upload", bytes.NewReader(make([]byte, size))))
if rec.Code != want {
t.Errorf("size %d: %d, want %d", size, rec.Code, want)
}
}
}
func TestTimeoutHandlerAnswers503(t *testing.T) {
srv := httptest.NewServer(Budget(Slow(time.Second), 30*time.Millisecond))
defer srv.Close()
start := time.Now()
resp, err := srv.Client().Get(srv.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusServiceUnavailable || string(body) != "request budget exhausted" {
t.Fatalf("%d %q", resp.StatusCode, body)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("took %v", time.Since(start))
}
}
func TestErrAbortHandlerBreaksResponseWithoutLogging(t *testing.T) {
var logs bytes.Buffer
srv := httptest.NewUnstartedServer(http.HandlerFunc(Abort))
srv.Config.ErrorLog = log.New(&logs, "", 0)
srv.Start()
defer srv.Close()
resp, err := srv.Client().Get(srv.URL)
if err == nil {
_, err = io.ReadAll(resp.Body)
resp.Body.Close()
}
if err == nil {
t.Fatal("client should see a broken response")
}
if strings.Contains(logs.String(), "panic") {
t.Fatalf("server logged: %s", logs.String())
}
}Writing the response: ResponseWriter, Header().Set, WriteHeader, http.Error Must-know
In plain words: Set headers first, then call WriteHeader(status) once, then Write the body. The first Write without a WriteHeader sends 200. Once the status line is out, header changes are ignored.
Common misunderstanding: "http.Error ends the handler." It writes a response and returns; your code continues. The doc: "It does not otherwise end the request; the caller should ensure no further writes are done to w." Forgetting return after it produces the log line http: superfluous response.WriteHeader call and a body with two messages glued together.
Definition: Header() "returns the header map that will be sent by [ResponseWriter.WriteHeader]". "Changing the header map after a call to [ResponseWriter.WriteHeader] (or [ResponseWriter.Write]) has no effect unless the HTTP status code was of the 1xx class or the modified headers are trailers." Write calls WriteHeader(http.StatusOK) if needed and, without a Content-Type, sets one from DetectContentType on the first 512 bytes; small unflushed responses get a Content-Length automatically. WriteHeader "must be a valid HTTP 1xx-5xx status code"; any number of 1xx, "followed by at most one 2xx-5xx header". http.Error "deletes the Content-Length header, sets Content-Type to “text/plain; charset=utf-8”, and sets X-Content-Type-Options to “nosniff”." Header().Set canonicalises keys (x-request-id becomes X-Request-Id); Add appends a second value.
1 w.Header().Set("Content-Type", "application/json") map only, nothing sent
2 w.Header().Set("Location", "/users/7")
3 w.WriteHeader(201) status + headers queued
4 w.Header().Set("X-Late", "1") ignored
5 w.Write(body) body buffered (4 KB) or flushed
6 w.WriteHeader(500) ignored; log: superfluous response.WriteHeader call
7 return server flushes, adds Content-Length if it canReal scenario: a handler that sets Content-Type after writing and serves JSON as text/plain; an error path that writes 500 after a 200 was already sent by an early Write (the client sees 200 and a broken body); a CSV export with Content-Disposition: attachment; trailers carrying a checksum after a streamed body.
| Call | Effect | Pitfall |
|---|---|---|
w.Header().Set(k, v) | Replace header | After WriteHeader: no effect |
w.Header().Add(k, v) | Append value | Duplicates on retry paths |
w.Header()["Date"] = nil | Suppress automatic header | Rarely needed |
w.WriteHeader(code) | Send status | Second call ignored and logged |
w.Write(b) | Body; implicit 200 | Content type sniffed if unset |
http.Error(w, msg, code) | Plain-text error | Does not return for you |
http.NotFound(w, r) | 404 page not found | Plain text, not JSON |
Fix / how to use it: one helper writes success (jsonio.Write), one writes errors (jsonio.Problem), both set headers before the status; handlers return right after calling either.
Status codes Important
In plain words: The status code is the machine-readable result. Clients, proxies, retries and dashboards decide on it, not on your JSON message. Pick it from RFC 9110 and use the http.Status* constants.
Common misunderstanding: "Everything that failed is a 500" or "200 with an error field in the JSON is fine." A 500 tells a retrying client to try again and pages someone; a validation failure is the client's fault (4xx) and must not be retried. And 400 vs 422: RFC 9110 says 422 means the server "understands the content type of the request content (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request content is correct, but it was unable to process the contained instructions".
Definition: five classes: 1xx informational, 2xx success, 3xx redirection, 4xx client error, 5xx server error. http.StatusText(code) gives the reason phrase. ServeMux itself writes 404, 405 (with Allow), 307 for trailing-slash and path-cleaning redirects, and 400 for some malformed requests; the server writes 431 for oversized headers and 400 for unparsable requests.
decision for POST /users {"name": ""}
1 body not JSON content type -> 415
2 body over limit -> 413
3 JSON syntax error / unknown field -> 400
4 valid JSON, name empty -> 422
5 conflict (email exists) -> 409
6 created -> 201 + Location: /users/7
7 database down -> 503 (retryable) or 500Real scenario: a mobile client that retries 5xx but not 4xx; an API gateway that turns your 504 into its own error page; a monitoring SLO that counts only 5xx as errors (so a validation bug shown as 500 burns your error budget); DELETE returning 204 twice in a row because delete is idempotent.
| Situation | Code | Retry? | Body |
|---|---|---|---|
| Read OK | 200 | n/a | Resource |
| Created | 201 | n/a | Resource + Location |
| Accepted for async work | 202 | n/a | Job id |
| Deleted / updated, nothing to say | 204 | n/a | None |
| Malformed request | 400 | No | Problem details |
| Not authenticated / not allowed | 401 / 403 | No | Problem details |
| Wrong method | 405 | No | Allow header |
| Conflict, version mismatch | 409 / 412 | After re-read | Problem details |
| Validation failed | 422 | No | Field errors |
| Rate limited | 429 | After Retry-After | Problem details |
| Bug | 500 | Maybe | Generic message, details in logs |
| Upstream failed / too slow | 502 / 504 | Yes (idempotent) | Problem details |
| Overloaded, shutting down | 503 | Yes, with Retry-After | Problem details |
Fix / how to use it: map errors to codes in one place (jsonio.Fail, the switch in userReviews); resource and status design at the API level is in REST API Design.
JSON request/response helpers, encoding/json streaming and content negotiation Must-know
In plain words: Two helpers cover most APIs: Decode reads exactly one bounded JSON value into a struct and maps every failure to 400, 413 or 415; Write sets the headers, the status and encodes. For big results, stream with json.Encoder one object per line and flush. Content negotiation means looking at Accept to choose the format.
Common misunderstanding: "json.NewDecoder(r.Body).Decode(&v) validates the body." It stops after the first value, so {"a":1} garbage is accepted; it ignores unknown fields, so a typo like "nmae" silently leaves Name empty; and it reads without limit. json.Unmarshal(io.ReadAll(r.Body)) buffers the whole body first. Since Go 1.27 encoding/json "is now backed by the v2 implementation", and "the exact text of error messages may differ", so match on error types (*json.SyntaxError, *json.UnmarshalTypeError), not on strings.
Definition: Decoder "reads and decodes JSON values from an input stream"; DisallowUnknownFields "causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields"; More "reports whether there is another element in the current array or object being parsed". Encoder.Encode writes the value "followed by a newline character", which makes NDJSON free. SetEscapeHTML defaults to escaping &, < and >. Struct tags and the v2 API are in JSON, XML & Encoder/Decoder.
Decode(w, r, &in, 16<<10)
1 Content-Type: text/plain -> 415 "Content-Type must be application/json"
2 r.Body = MaxBytesReader(..., 16 KB)
3 dec.DisallowUnknownFields()
4 dec.Decode(&in) {"nmae":"x"} -> 400 json: unknown field "nmae"
5 dec.Decode(&in) ok
6 dec.Decode(&struct{}{}) != io.EOF -> 400 "body must contain a single JSON value"
6b ...unless that second read hit the limit ({"name":"a"} + 100 spaces, limit 32) -> 413
7 handler validates fields -> 422 on business rulesReal scenario: a public API where clients misspell fields and need to hear about it; an export endpoint streaming 2 million rows as NDJSON without holding them in memory; a report endpoint that returns JSON to the SPA and CSV when Excel asks (Accept: text/csv); error bodies in RFC 9457 "Problem Details for HTTP APIs" (application/problem+json).
| Need | stdlib | Note |
|---|---|---|
| Strict decode | Decoder + DisallowUnknownFields + second Decode == io.EOF | The helper below |
Big numbers in any | dec.UseNumber() | Avoids float64 rounding of ids |
| Stream an array in | dec.Token() + dec.More() loop | Constant memory |
| Stream out | enc.Encode(item) per item + Flush | NDJSON (application/x-ndjson) |
| Pretty output | enc.SetIndent("", " ") | Debug only |
| Negotiate | Accept header, mime.ParseMediaType; q=0 means "not acceptable" (RFC 9110) | 406 when nothing fits |
| Vary caches | w.Header().Set("Vary", "Accept") | Needed when the body depends on Accept |
Fix / how to use it:
// Package jsonio holds the JSON request/response helpers a net/http
// service needs: a bounded, strict decoder, a writer that sets the
// headers before the status, a problem response, simple content
// negotiation and NDJSON streaming with json.Encoder.
package jsonio
import (
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strconv"
"strings"
)
// MaxBody is the default request body limit (1 MiB).
const MaxBody = 1 << 20
// RequestError carries the HTTP status a decode failure maps to.
type RequestError struct {
Status int
Msg string
}
func (e *RequestError) Error() string { return e.Msg }
// Decode reads exactly one JSON value from r.Body into dst.
// It enforces Content-Type, a size limit (http.MaxBytesReader),
// unknown-field rejection and the absence of trailing data.
func Decode(w http.ResponseWriter, r *http.Request, dst any, limit int64) error {
if ct := r.Header.Get("Content-Type"); ct != "" {
mt, _, err := mime.ParseMediaType(ct)
if err != nil || mt != "application/json" {
return &RequestError{http.StatusUnsupportedMediaType, "Content-Type must be application/json"}
}
}
r.Body = http.MaxBytesReader(w, r.Body, limit)
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
var maxErr *http.MaxBytesError
var syntaxErr *json.SyntaxError
var typeErr *json.UnmarshalTypeError
switch {
case errors.As(err, &maxErr):
return &RequestError{http.StatusRequestEntityTooLarge, fmt.Sprintf("body larger than %d bytes", maxErr.Limit)}
case errors.Is(err, io.EOF):
return &RequestError{http.StatusBadRequest, "body must not be empty"}
case errors.As(err, &syntaxErr), errors.Is(err, io.ErrUnexpectedEOF):
return &RequestError{http.StatusBadRequest, "malformed JSON"}
case errors.As(err, &typeErr):
return &RequestError{http.StatusBadRequest, fmt.Sprintf("field %q has the wrong type", typeErr.Field)}
case strings.HasPrefix(err.Error(), "json: unknown field"):
return &RequestError{http.StatusBadRequest, err.Error()}
default:
return &RequestError{http.StatusBadRequest, "invalid body"}
}
}
// A second Decode must hit EOF: "{...}{...}" or "{...} junk" is rejected.
// The size limit can also be reached here (a small value followed by
// padding), and that is still 413, not 400.
err := dec.Decode(&struct{}{})
var maxErr *http.MaxBytesError
switch {
case errors.Is(err, io.EOF):
return nil
case errors.As(err, &maxErr):
return &RequestError{http.StatusRequestEntityTooLarge, fmt.Sprintf("body larger than %d bytes", maxErr.Limit)}
default:
return &RequestError{http.StatusBadRequest, "body must contain a single JSON value"}
}
}
// Write encodes v as JSON with the given status. Headers are set
// before WriteHeader, because changes after it have no effect.
func Write(w http.ResponseWriter, status int, v any) error {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(status)
return json.NewEncoder(w).Encode(v)
}
// Problem writes an RFC 9457 style error body.
func Problem(w http.ResponseWriter, status int, detail string) {
w.Header().Set("Content-Type", "application/problem+json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(map[string]any{
"title": http.StatusText(status),
"status": status,
"detail": detail,
})
}
// Fail maps any error from Decode to a response.
func Fail(w http.ResponseWriter, err error) {
var re *RequestError
if errors.As(err, &re) {
Problem(w, re.Status, re.Msg)
return
}
Problem(w, http.StatusInternalServerError, "internal error")
}
// Negotiate picks the first offered media type the Accept header allows.
// A range with q=0 is "not acceptable" (RFC 9110, 12.4.2) and excludes the
// offers it matches. Other q-values are not weighed here: a full parser sorts
// by q and specificity (RFC 9110, 12.5.1).
func Negotiate(r *http.Request, offers ...string) (string, bool) {
accept := r.Header.Get("Accept")
if accept == "" {
return offers[0], true
}
type rng struct {
mt string
forbidden bool
}
var ranges []rng
for _, part := range strings.Split(accept, ",") {
mt, params, err := mime.ParseMediaType(strings.TrimSpace(part))
if err != nil {
continue
}
q := 1.0
if v, ok := params["q"]; ok {
if f, err := strconv.ParseFloat(v, 64); err == nil {
q = f
}
}
ranges = append(ranges, rng{mt, q <= 0})
}
matches := func(mt, o string) bool {
return mt == o || mt == "*/*" || (strings.HasSuffix(mt, "/*") && strings.HasPrefix(o, strings.TrimSuffix(mt, "*")))
}
allowed := func(o string) bool {
// The most specific range that matches o decides (exact beats type/* beats */*).
best, bestLen := rng{}, -1
for _, rg := range ranges {
if matches(rg.mt, o) && len(strings.TrimRight(rg.mt, "*")) > bestLen {
best, bestLen = rg, len(strings.TrimRight(rg.mt, "*"))
}
}
return bestLen >= 0 && !best.forbidden
}
for _, rg := range ranges {
if rg.forbidden {
continue
}
for _, o := range offers {
if matches(rg.mt, o) && allowed(o) {
return o, true
}
}
}
return "", false
}
// StreamNDJSON writes one JSON object per line as items arrive, flushing
// after each, so memory stays flat however many rows there are.
func StreamNDJSON[T any](w http.ResponseWriter, r *http.Request, items <-chan T) error {
w.Header().Set("Content-Type", "application/x-ndjson")
rc := http.NewResponseController(w)
enc := json.NewEncoder(w)
for {
select {
case <-r.Context().Done():
return r.Context().Err()
case it, ok := <-items:
if !ok {
return nil
}
if err := enc.Encode(it); err != nil {
return err
}
if err := rc.Flush(); err != nil {
return err
}
}
}
}package jsonio
import (
"bufio"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
type input struct {
Name string `json:"name"`
Price int `json:"price"`
}
func TestDecodeMapsFailuresToStatus(t *testing.T) {
cases := []struct {
name, ct, body string
limit int64
want int
}{
{"ok", "application/json", `{"name":"pen","price":3}`, MaxBody, 0},
{"empty", "application/json", ``, MaxBody, 400},
{"syntax", "application/json", `{"name":`, MaxBody, 400},
{"type", "application/json", `{"price":"three"}`, MaxBody, 400},
{"unknown field", "application/json", `{"nmae":"pen"}`, MaxBody, 400},
{"two values", "application/json", `{"name":"a"}{"name":"b"}`, MaxBody, 400},
{"too large", "application/json", `{"name":"` + strings.Repeat("x", 100) + `"}`, 32, 413},
{"media type", "text/plain", `{"name":"pen"}`, MaxBody, 415},
// The first value fits; the limit is hit while checking for trailing data.
{"too large after first value", "application/json", `{"name":"a"}` + strings.Repeat(" ", 100), 32, 413},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
r := httptest.NewRequest(http.MethodPost, "/items", strings.NewReader(c.body))
r.Header.Set("Content-Type", c.ct)
rec := httptest.NewRecorder()
var in input
err := Decode(rec, r, &in, c.limit)
if c.want == 0 {
if err != nil || in.Name != "pen" {
t.Fatalf("got %+v, %v", in, err)
}
return
}
Fail(rec, err)
if rec.Code != c.want {
t.Fatalf("status %d, want %d (%v)", rec.Code, c.want, err)
}
})
}
}
func TestWriteSetsHeadersBeforeStatus(t *testing.T) {
rec := httptest.NewRecorder()
if err := Write(rec, http.StatusCreated, map[string]int{"id": 7}); err != nil {
t.Fatal(err)
}
// Result().Header is the snapshot taken at WriteHeader time, so a header
// set after WriteHeader would be missing here (rec.Header() would still show it).
res := rec.Result()
if res.StatusCode != 201 || res.Header.Get("Content-Type") != "application/json; charset=utf-8" || rec.Body.String() != "{\"id\":7}\n" {
t.Fatalf("%d %q %q", res.StatusCode, res.Header.Get("Content-Type"), rec.Body.String())
}
}
func TestNegotiate(t *testing.T) {
cases := map[string]string{
"": "application/json",
"text/csv": "text/csv",
"text/*;q=0.9": "text/csv",
"application/xml, */*;q=0.1": "application/json",
"image/png": "",
"application/json;q=0": "", // q=0 means "not acceptable"
"application/json;q=0, text/csv": "text/csv",
"*/*;q=0": "",
}
for accept, want := range cases {
r := httptest.NewRequest(http.MethodGet, "/report", nil)
if accept != "" {
r.Header.Set("Accept", accept)
}
got, _ := Negotiate(r, "application/json", "text/csv")
if got != want {
t.Errorf("Accept %q: got %q, want %q", accept, got, want)
}
}
}
func TestStreamNDJSONFlushesEachLine(t *testing.T) {
items := make(chan input)
seen := make(chan struct{})
stalled := make(chan int, 1) // index of the item the client never saw in time
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = StreamNDJSON(w, r, items)
}))
defer srv.Close()
go func() {
defer close(items)
for i := range 3 {
items <- input{Name: "row", Price: i}
// The next item is produced only after the client has read this
// line, which can happen only if the handler flushed it.
select {
case <-seen:
case <-time.After(500 * time.Millisecond):
stalled <- i
return
}
}
}()
resp, err := srv.Client().Get(srv.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
sc := bufio.NewScanner(resp.Body)
n := 0
for sc.Scan() {
n++
select {
case seen <- struct{}{}:
case <-time.After(time.Second):
}
}
select {
case i := <-stalled:
t.Fatalf("line %d was not flushed while the handler was still running", i)
default:
}
if n != 3 {
t.Fatalf("got %d lines", n)
}
}Static files: http.FileServer, ServeFileFS, embed static, http.StripPrefix Important
In plain words: http.FileServerFS(fsys) serves a whole file tree with correct Content-Type, Range, directory listings, and Last-Modified/If-Modified-Since when the file has a modification time (embedded files do not). http.ServeFileFS(w, r, fsys, name) serves one file. With //go:embed, the files live inside the binary. http.StripPrefix removes the URL prefix so /static/app.css looks up app.css.
Common misunderstanding: "http.FileServer(http.Dir(".")) is a quick way to serve assets." It serves everything in the working directory, including .env and .git, with directory listings on. Serve a dedicated directory or an embedded sub-tree. And os.DirFS is not a sandbox: its doc says that if "/prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does" and points to Root.FS instead. What http.FS/FileServerFS do guarantee is narrower: request paths are cleaned and must be valid io/fs names (no .. element), so the URL alone cannot climb out; what the fs.FS does with a valid name is up to the fs.FS. Another: forgetting StripPrefix, so /static/app.css is looked up as static/app.css inside a tree that has no static directory, and every asset is 404.
Definition: FileServerFS and ServeFileFS arrived in Go 1.22 as "versions of the existing ServeFile, FileServer, and NewFileTransport, operating on an fs.FS"; http.FileServer(http.FS(fsys)) was the Go 1.16 way. StripPrefix "returns a handler that serves HTTP requests by removing the given prefix from the request URL's Path (and RawPath if set) and invoking the handler h", and answers 404 when the prefix is absent. fs.Sub(assets, "assets") removes the directory name that //go:embed assets keeps. Since Go 1.23, ServeContent, ServeFile and ServeFileFS "remove the Cache-Control, Content-Encoding, Etag, and Last-Modified headers when serving an error". Files in an embed.FS report a zero ModTime, and fs.go sets Last-Modified only when the time is not zero, so embedded assets get no Last-Modified; if you set an ETag header before calling the file server, ServeContent uses it for If-None-Match and answers 304. The snippet computes a content-hash ETag per file at startup, sends Cache-Control: public, max-age=31536000, immutable only for fingerprinted names (app.3f2a9c1e.css), and no-cache (always revalidate) for names that can change in place (app.css, index.html).
1 GET /static/app.css
2 mux: "GET /static/" ─▶ cachePolicy (ETag, Cache-Control) ─▶ StripPrefix("/static/") ─▶ path "app.css"
3 FileServerFS(sub): open sub/app.css (embed.FS, read-only, in the binary)
4 Content-Type: text/css; charset=utf-8, ETag, Cache-Control: no-cache, Accept-Ranges: bytes (no Last-Modified: embed ModTime is zero)
4b If-None-Match: <same ETag> -> 304 Not Modified; app.3f2a9c1e.css -> Cache-Control: ... immutable
5 Range: bytes=0-3 -> 206 "body"
6 GET /static/../static.go -> ServeMux cleans the path: 307 to /static.go, never escapes the FSReal scenario: a single binary with the admin SPA embedded; a docs site served from embed.FS with fingerprinted asset names cached for a year and unfingerprinted ones revalidated by ETag; a download endpoint that serves one file per user with ServeFileFS and a computed name; a dev mode that serves from os.DirFS("web") so edits show without rebuilding.
| API | Source | Since | Use |
|---|---|---|---|
http.FileServer(http.Dir(d)) | OS directory | 1.0 | Legacy; beware what d contains |
http.FileServer(http.FS(fsys)) | any fs.FS | 1.16 | Pre-1.22 code |
http.FileServerFS(fsys) | any fs.FS | 1.22 | Default choice |
http.ServeFileFS(w, r, fsys, name) | one file | 1.22 | Index page, downloads |
http.ServeContent(w, r, name, mod, rs) | any io.ReadSeeker | 1.0 | Generated files, blobs |
//go:embed + embed.FS | compiled in | 1.16 | Single-binary deploys |
os.DirFS(dir) | OS directory; names cannot contain .., but symlinks inside can point outside | 1.16 | Dev mode on trusted trees |
os.OpenRoot(dir) + root.FS() | OS directory, symlink escapes blocked | 1.24 | Uploads, user-influenced trees |
Fix / how to use it: the details of embed and io/fs are in Files, Directories & embed; this is the HTTP side:
// Package static serves files embedded in the binary with
// http.FileServerFS, http.StripPrefix and http.ServeFileFS (Go 1.22).
//
// Files in an embed.FS have a zero ModTime, so FileServerFS sends no
// Last-Modified header. The handler adds a content-hash ETag instead, so
// browsers can revalidate (If-None-Match -> 304), and it caches for a year
// only names that carry a content fingerprint (app.3f2a9c1e.css).
package static
import (
"crypto/sha256"
"embed"
"encoding/hex"
"io/fs"
"net/http"
"path"
"regexp"
"strings"
)
//go:embed assets
var assets embed.FS
// fingerprinted matches names like app.3f2a9c1e.css (8+ hex digits before the extension).
var fingerprinted = regexp.MustCompile(`\.[0-9a-f]{8,}\.[a-z0-9]+$`)
// Register mounts /static/ and the index page on mux.
func Register(mux *http.ServeMux) {
sub, err := fs.Sub(assets, "assets") // strip the "assets/" directory name
if err != nil {
panic(err)
}
etags := hashAll(sub)
// /static/app.css -> StripPrefix -> /app.css -> sub/app.css
files := http.StripPrefix("/static/", http.FileServerFS(sub))
mux.Handle("GET /static/", cachePolicy(etags, files))
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("ETag", etags["index.html"])
http.ServeFileFS(w, r, sub, "index.html")
})
}
// hashAll computes a strong ETag per file once, at startup.
func hashAll(fsys fs.FS) map[string]string {
etags := map[string]string{}
_ = fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
b, err := fs.ReadFile(fsys, p)
if err != nil {
return err
}
sum := sha256.Sum256(b)
etags[p] = `"` + hex.EncodeToString(sum[:8]) + `"`
return nil
})
return etags
}
// cachePolicy sets ETag (ServeContent then answers If-None-Match with 304)
// and Cache-Control: immutable only for fingerprinted names, no-cache otherwise.
func cachePolicy(etags map[string]string, h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(path.Clean(r.URL.Path), "/static/")
if tag, ok := etags[name]; ok {
w.Header().Set("ETag", tag)
}
if fingerprinted.MatchString(name) {
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
} else {
w.Header().Set("Cache-Control", "no-cache") // revalidate every time
}
h.ServeHTTP(w, r)
})
}package static
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func get(t *testing.T, path string, hdr ...string) *httptest.ResponseRecorder {
t.Helper()
mux := http.NewServeMux()
Register(mux)
r := httptest.NewRequest(http.MethodGet, path, nil)
for i := 0; i+1 < len(hdr); i += 2 {
r.Header.Set(hdr[i], hdr[i+1])
}
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, r)
return rec
}
func TestStatic(t *testing.T) {
cases := []struct {
path, wantCT string
code int
}{
{"/", "text/html; charset=utf-8", 200},
{"/static/app.css", "text/css; charset=utf-8", 200},
{"/static/missing.js", "text/plain; charset=utf-8", 404},
{"/static/../static.go", "", 307}, // cleaned by ServeMux, never escapes the FS
}
for _, c := range cases {
rec := get(t, c.path)
if rec.Code != c.code || (c.wantCT != "" && rec.Header().Get("Content-Type") != c.wantCT) {
t.Errorf("%s = %d %q", c.path, rec.Code, rec.Header().Get("Content-Type"))
}
}
}
func TestCachePolicyDependsOnFingerprint(t *testing.T) {
if cc := get(t, "/static/app.3f2a9c1e.css").Header().Get("Cache-Control"); !strings.Contains(cc, "immutable") {
t.Errorf("fingerprinted asset: Cache-Control %q, want immutable", cc)
}
if cc := get(t, "/static/app.css").Header().Get("Cache-Control"); cc != "no-cache" {
t.Errorf("plain asset: Cache-Control %q, want no-cache (same URL, new content on deploy)", cc)
}
}
func TestEmbeddedFilesHaveNoLastModifiedButRevalidateByETag(t *testing.T) {
rec := get(t, "/static/app.css")
if lm := rec.Header().Get("Last-Modified"); lm != "" {
t.Fatalf("Last-Modified %q: embed.FS files have a zero ModTime", lm)
}
etag := rec.Header().Get("ETag")
if etag == "" {
t.Fatal("no ETag")
}
if code := get(t, "/static/app.css", "If-None-Match", etag).Code; code != http.StatusNotModified {
t.Fatalf("revalidation: %d, want 304", code)
}
}
func TestRange(t *testing.T) {
rec := get(t, "/static/app.css", "Range", "bytes=0-3")
if rec.Code != http.StatusPartialContent || rec.Body.String() != "body" {
t.Fatalf("range: %d %q", rec.Code, rec.Body.String())
}
}Cookies and redirects Important
In plain words: http.SetCookie(w, &http.Cookie{...}) adds a Set-Cookie header; r.Cookie("name") reads one back. http.Redirect(w, r, url, code) sends a 3xx with Location. After a successful form POST, answer 303 so a browser refresh does not resubmit.
Common misunderstanding: "301 and 302 keep the method." Browsers historically change a redirected POST into a GET for 301 and 302; use 307 (temporary) or 308 (permanent) to keep method and body, and 303 when you want the GET. RFC 9110 lets the follow-up of a 303 be "a GET or HEAD request if using HTTP", and Go's client keeps GET and HEAD as they are for 301, 302 and 303 and turns every other method into GET (redirectBehavior in client.go). And for cookies: a session cookie without HttpOnly, Secure and SameSite is readable by injected scripts, sent over plain HTTP and attached to cross-site POSTs.
Definition: RFC 9110: 303 "indicates that the server is redirecting the user agent to a different resource ... which is intended to provide an indirect response to the original request"; 308 "indicates that the target resource has been assigned a new permanent URI". http.Redirect's code "should be in the 3xx range"; when no Content-Type is set it writes a small HTML body. RFC 6265: "The HttpOnly attribute limits the scope of the cookie to HTTP requests." Cookie.MaxAge < 0 means "delete now" (Max-Age=0 on the wire); SameSite values are SameSiteLaxMode, SameSiteStrictMode, SameSiteNoneMode. The client follows up to 10 redirects ("stop after 10 consecutive requests") and does not forward Authorization or Cookie to a different domain.
browser Go server
1 POST /login user=ana ───▶ validate; SetCookie(session=s-ana; HttpOnly; Secure; SameSite=Lax)
2 ◀─── 303 See Other, Location: /dashboard
3 GET /dashboard ───▶ r.Cookie("session") -> s-ana
Cookie: session=s-ana
4 ◀─── 200 hello s-ana
5 F5 (refresh) ───▶ GET /dashboard again, not a second POSTReal scenario: Post/Redirect/Get after creating an order; an old URL moved permanently with 308 so API clients keep POSTing; a logout that expires the cookie; an OAuth callback redirecting back to the app with a 302; a cookie jar (net/http/cookiejar) in an integration test that logs in and follows redirects.
| Code | Constant | Method kept? | Cached? | Use |
|---|---|---|---|---|
| 301 | StatusMovedPermanently | Browsers and Go's client switch POST to GET | Yes | Permanent move of GET pages |
| 302 | StatusFound | Browsers and Go's client switch POST to GET | No | Temporary, legacy |
| 303 | StatusSeeOther | No: GET (HEAD stays HEAD) | No | After form POST (PRG) |
| 307 | StatusTemporaryRedirect | Yes | No | Temporary, APIs; ServeMux slash redirect since 1.26 |
| 308 | StatusPermanentRedirect | Yes | Yes | Permanent move of an API |
| Cookie field | Wire attribute | Recommended for sessions |
|---|---|---|
HttpOnly: true | HttpOnly | Always |
Secure: true | Secure | Always (HTTPS only) |
SameSite: http.SameSiteLaxMode | SameSite=Lax | Default; Strict for admin |
Path: "/" | Path=/ | Usually |
MaxAge: n | Max-Age=n | Session lifetime |
Partitioned: true (1.23) | Partitioned | Third-party embeds (CHIPS) |
Fix / how to use it: sessions, CSRF tokens and password flows are in Authentication in Go; cookie and CORS design in Web Sessions, Cookies & CORS.
// Package web shows cookies and redirects: Set-Cookie attributes,
// reading a cookie, Post/Redirect/Get with 303, and a permanent 308.
package web
import (
"errors"
"fmt"
"net/http"
"time"
)
// Register mounts the login flow on mux.
func Register(mux *http.ServeMux) {
mux.HandleFunc("POST /login", login)
mux.HandleFunc("GET /dashboard", dashboard)
mux.HandleFunc("POST /logout", logout)
// Moved resource: 308 keeps the method and body, 301 lets clients turn POST into GET.
mux.Handle("/old-dashboard", http.RedirectHandler("/dashboard", http.StatusPermanentRedirect))
}
func login(w http.ResponseWriter, r *http.Request) {
if r.PostFormValue("user") == "" {
http.Error(w, "user required", http.StatusUnprocessableEntity)
return
}
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "s-" + r.PostFormValue("user"), // real code: a random id stored server-side
Path: "/",
MaxAge: int((8 * time.Hour).Seconds()),
HttpOnly: true, // not readable from JavaScript
Secure: true, // HTTPS only
SameSite: http.SameSiteLaxMode, // not sent on cross-site POSTs
})
// Post/Redirect/Get: 303 tells the browser to GET the next page.
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
func dashboard(w http.ResponseWriter, r *http.Request) {
c, err := r.Cookie("session")
if errors.Is(err, http.ErrNoCookie) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
fmt.Fprintf(w, "hello %s", c.Value)
}
func logout(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{Name: "session", Value: "", Path: "/", MaxAge: -1}) // Max-Age=0 on the wire
http.Redirect(w, r, "/login", http.StatusSeeOther)
}package web
import (
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
func TestLoginSetsCookieAndRedirects(t *testing.T) {
mux := http.NewServeMux()
Register(mux)
r := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader("user=ana"))
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, r)
sc := rec.Header().Get("Set-Cookie")
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/dashboard" {
t.Fatalf("%d %q", rec.Code, rec.Header().Get("Location"))
}
for _, attr := range []string{"session=s-ana", "Path=/", "Max-Age=28800", "HttpOnly", "Secure", "SameSite=Lax"} {
if !strings.Contains(sc, attr) {
t.Errorf("Set-Cookie %q lacks %s", sc, attr)
}
}
}
func TestClientFollows303WithCookieJar(t *testing.T) {
mux := http.NewServeMux()
Register(mux)
srv := httptest.NewTLSServer(mux) // Secure cookies need HTTPS
defer srv.Close()
jar, _ := cookiejar.New(nil)
c := srv.Client()
c.Jar = jar
resp, err := c.PostForm(srv.URL+"/login", url.Values{"user": {"ana"}})
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
// The client turned the POST into GET /dashboard and sent the cookie.
if resp.Request.Method != http.MethodGet || string(b) != "hello s-ana" {
t.Fatalf("%s %q", resp.Request.Method, b)
}
}
func TestRedirect308KeepsMethod(t *testing.T) {
mux := http.NewServeMux()
Register(mux)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/old-dashboard", nil))
if rec.Code != http.StatusPermanentRedirect || rec.Header().Get("Location") != "/dashboard" {
t.Fatalf("%d %q", rec.Code, rec.Header().Get("Location"))
}
}
func TestNoCookieRedirectsToLogin(t *testing.T) {
mux := http.NewServeMux()
Register(mux)
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/dashboard", nil))
if rec.Code != http.StatusFound {
t.Fatalf("%d", rec.Code)
}
}Server timeouts: ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout Must-know
In plain words: Four fields on http.Server decide how long a connection may take to send its headers, its whole request, to receive the response, and to sit idle between keep-alive requests. All four default to zero, which means "forever".
Common misunderstanding: "WriteTimeout is the time my handler has." It is a deadline on the connection, set when the request headers have been read; when it passes, writes fail and the connection is closed, but your handler keeps running, and the client sees a reset instead of a status code. And deadlines do not slide: Cloudflare's guide warns that "all timeouts are implemented in terms of Deadlines, so they do NOT reset every time data is sent or received."
Definition: from server.go: ReadTimeout "is the maximum duration for reading the entire request, including the body"; "most users will prefer to use ReadHeaderTimeout. It is valid to use them both." ReadHeaderTimeout "is the amount of time allowed to read request headers. The connection's read deadline is reset after reading the headers and the Handler can decide what is considered too slow for the body. If zero, the value of ReadTimeout is used." WriteTimeout "is the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read." IdleTimeout "is the maximum amount of time to wait for the next request when keep-alives are enabled. If zero, the value of ReadTimeout is used." This page's one-line summary of the set: timeouts (ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout).
slowloris against http.ListenAndServe (all timeouts 0)
1 attacker opens 10,000 TCP connections
2 each sends "GET / HTTP/1.1\r\n" then one header byte every 30 s
3 server: 10,000 goroutines blocked in readRequest, 10,000 fds
4 ulimit reached: accept fails "too many open files"; real users get nothing
with ReadHeaderTimeout: 5s
5 each connection is closed 5 s after accept; goroutines and fds returnReal scenario: a public API behind a load balancer whose idle timeout is 60 s, so IdleTimeout must be shorter or the LB reuses connections the server already closed (or the other way round, depending on which side you control); an upload endpoint that needs 5 minutes for the body but 5 seconds for headers; a streaming endpoint that cannot live with a global WriteTimeout and extends it per write (see Streaming); a Go service exposed without a proxy that fell over to a slowloris.
| Field | Starts | Ends | Default | Typical API value |
|---|---|---|---|---|
ReadHeaderTimeout | Accept (or end of previous response) | Headers read | 0, falls back to ReadTimeout | 2–10 s |
ReadTimeout | Accept | Body read | 0 | 10–60 s, or 0 with per-request deadlines |
WriteTimeout | Headers read (accept, for TLS) | Response written | 0 | > slowest handler budget |
IdleTimeout | Response done | Next request starts | 0, falls back to ReadTimeout | 60–120 s |
MaxHeaderBytes | n/a | n/a | 1 MB | 64 KB–1 MB |
ResponseController.SetReadDeadline | Call | Body read | n/a | Per upload route |
ResponseController.SetWriteDeadline | Call | Next writes | n/a | Per streaming write |
Fix / how to use it: always construct the server; never call the package-level ListenAndServe:
// Package server builds an http.Server with every timeout set and runs it
// with graceful shutdown: stop accepting, let in-flight requests finish,
// and treat http.ErrServerClosed as a normal exit.
package server
import (
"context"
"errors"
"log/slog"
"net"
"net/http"
"time"
)
// New returns a server whose connections cannot be held open forever.
// base becomes the root of every r.Context() via BaseContext.
func New(addr string, h http.Handler, base context.Context) *http.Server {
return &http.Server{
Addr: addr,
Handler: h,
ReadHeaderTimeout: 5 * time.Second, // slowloris: headers must arrive quickly
ReadTimeout: 30 * time.Second, // whole request including body
WriteTimeout: 30 * time.Second, // from end of headers to end of response
IdleTimeout: 90 * time.Second, // keep-alive connection waiting for the next request
MaxHeaderBytes: 64 << 10,
BaseContext: func(net.Listener) context.Context { return base },
}
}
// Serve runs srv on ln until ctx is done, then shuts down within grace.
// The caller usually builds ctx with signal.NotifyContext(..., SIGINT, SIGTERM).
func Serve(ctx context.Context, srv *http.Server, ln net.Listener, grace time.Duration) error {
errc := make(chan error, 1)
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc: // failed before any shutdown was asked for
return err
case <-ctx.Done():
}
slog.Info("shutting down", "grace", grace)
sctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), grace)
defer cancel()
err := srv.Shutdown(sctx) // closes listeners, closes idle conns, waits for active ones
if serveErr := <-errc; !errors.Is(serveErr, http.ErrServerClosed) {
return serveErr
}
if err != nil {
_ = srv.Close() // grace expired: cut the remaining connections
return err
}
return nil
}http.TimeoutHandler and ErrAbortHandler Important
In plain words: http.TimeoutHandler(h, d, msg) gives a handler a time budget: if h has not finished after d, the client gets 503 with msg, and h's context is canceled. panic(http.ErrAbortHandler) is the opposite tool: stop this response right now, without a log entry.
Common misunderstanding: "TimeoutHandler sends 504." The 2016 Cloudflare article says "sending a 504 Gateway Timeout", but the current doc and the test here say 503: "the handler responds with a 503 Service Unavailable error and the given message in its body". And it does not stop your code; it stops waiting for it (see context: TimeoutHandler). Because it buffers the whole response, it "supports the [Pusher] interface but does not support the [Hijacker] or [Flusher] interfaces", so it breaks streaming.
Definition: "After such a timeout, writes by h to its [ResponseWriter] will return [ErrHandlerTimeout]" (http: Handler timeout). For panics, the Handler doc: the server "recovers the panic, logs a stack trace to the server error log, and either closes the network connection or sends an HTTP/2 RST_STREAM"; "To abort a handler so the client sees an interrupted response but the server doesn't log an error, panic with the value [ErrAbortHandler]." httputil.ReverseProxy uses exactly this when the upstream dies mid-body.
TimeoutHandler(Slow(1s), 30ms, "request budget exhausted")
t=0 inner ctx = WithTimeout(r.Context(), 30ms); go Slow(tw, r)
t=30ms timer: cancel(); write 503 "request budget exhausted" (real test: 503 in ~30 ms)
t=30ms Slow sees ctx.Done(); its write returns http: Handler timeout
Abort: Content-Length: 100, writes "partial", panic(http.ErrAbortHandler)
1 server recovers, closes connection, logs nothing
2 client: unexpected EOF reading the body (real test: error, empty server log)Real scenario: a legacy report handler you cannot refactor yet but must cap at 2 s; a proxy that has already sent a 200 header when the upstream fails and must signal "broken" rather than send a truncated file as complete; a handler that detects a protocol violation mid-stream.
| Tool | Client sees | Logs | Streaming OK |
|---|---|---|---|
http.TimeoutHandler | 503 + message | No | No |
Middleware with context.WithTimeout | What the handler writes (504 in After) | Your choice | Yes |
Server.WriteTimeout | Connection reset, no status | No | Only with per-write deadlines |
panic(http.ErrAbortHandler) | Broken response | No | Yes |
| Any other panic | Broken response | Stack trace | Yes |
Fix / how to use it: prefer a per-route context budget that lets the handler pick 504 and log; keep TimeoutHandler for code you do not trust. The limits snippet above tests both.
Graceful shutdown: Shutdown, BaseContext, ErrServerClosed Must-know
In plain words: The two APIs of graceful shutdown (Shutdown, BaseContext) do different jobs. On SIGTERM, call srv.Shutdown(ctx): the server stops accepting, closes idle keep-alive connections, waits for running requests to finish, and returns. Serve returns http.ErrServerClosed at that moment, which is the normal exit, not an error.
Common misunderstanding: "Shutdown cancels in-flight requests." It waits for them; r.Context() is not canceled. If you want long handlers to notice, derive BaseContext from a context you cancel yourself. Second: "log.Fatal(srv.ListenAndServe())." ListenAndServe returns ErrServerClosed as soon as Shutdown starts, so log.Fatal exits the process before the in-flight requests finish. The doc: "Make sure the program doesn't exit and waits instead for Shutdown to return."
Definition: "Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, then closing all idle connections, and then waiting indefinitely for connections to return to idle and then shut down. If the provided context expires before the shutdown is complete, Shutdown returns the context's error". "Shutdown does not attempt to close nor wait for hijacked connections such as WebSockets"; register a notifier with RegisterOnShutdown. Close "immediately closes all active net.Listeners and any connections". A server cannot be reused after Shutdown. BaseContext "optionally specifies a function that returns the base context for incoming requests on this server", default context.Background(). ErrServerClosed is http: Server closed. Signal handling and the exit sequence of a whole process are in OS Processes, Signals & Graceful Shutdown.
kubelet / systemd main http.Server
1 SIGTERM ───────▶ NotifyContext ctx done
2 Serve(...): srv.Shutdown(grace 20s) ─▶ close listeners
3 Serve returns ErrServerClosed
4 close idle conns
5 (LB still sends for a few s: readiness should fail first) active request finishes, 200
6 Shutdown returns nil -> close DB pool, exit 0
7 SIGKILL after terminationGracePeriodSeconds if still alive ("defaults to 30 seconds", Kubernetes docs)Real scenario: a Kubernetes rolling deploy where every pod restart dropped a few requests until shutdown was added; a payment handler that must finish writing its row; a WebSocket hub that needs RegisterOnShutdown to tell clients to reconnect; a test suite that leaks servers because nobody calls Shutdown.
| Step | API | Note |
|---|---|---|
| Catch the signal | signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM) | In main |
| Stop accepting | srv.Shutdown(ctx) | Returns when idle or ctx done |
| Treat normal exit | errors.Is(err, http.ErrServerClosed) | From Serve/ListenAndServe |
| Bound the wait | context.WithTimeout(..., grace) | Below the orchestrator's kill timer |
| Cut the rest | srv.Close() | After grace expired |
| Long-lived conns | srv.RegisterOnShutdown(f) | WebSockets, SSE hubs |
| Tell handlers | BaseContext from a cancelable ctx | Optional; Shutdown itself does not |
| Keep-alives | Closed when idle | Clients reconnect to another pod |
Fix / how to use it: the Serve function above; its tests prove that an in-flight request completes with 200 after the stop signal, that Serve returns nil (not ErrServerClosed), that new connections are refused, and that an expired grace returns context.DeadlineExceeded.
package server
import (
"context"
"io"
"net"
"net/http"
"testing"
"time"
)
func TestGracefulShutdownLetsInFlightRequestFinish(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
started := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
time.Sleep(100 * time.Millisecond) // in-flight work
_, _ = io.WriteString(w, "finished")
})
ctx, stop := context.WithCancel(t.Context())
srv := New(ln.Addr().String(), h, t.Context())
done := make(chan error, 1)
go func() { done <- Serve(ctx, srv, ln, 2*time.Second) }()
type result struct {
body string
err error
}
res := make(chan result, 1)
go func() {
resp, err := http.Get("http://" + ln.Addr().String())
if err != nil {
res <- result{err: err}
return
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
res <- result{string(b), err}
}()
<-started
stop() // SIGTERM arrives while the request is running
if r := <-res; r.err != nil || r.body != "finished" {
t.Fatalf("in-flight request: %q %v", r.body, r.err)
}
if err := <-done; err != nil {
t.Fatalf("Serve returned %v, want nil (ErrServerClosed is normal)", err)
}
if _, err := net.DialTimeout("tcp", ln.Addr().String(), 200*time.Millisecond); err == nil {
t.Fatal("listener still accepting after shutdown")
}
}
func TestShutdownGraceExpires(t *testing.T) {
ln, _ := net.Listen("tcp", "127.0.0.1:0")
started := make(chan struct{})
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(started)
time.Sleep(time.Second)
})
ctx, stop := context.WithCancel(t.Context())
done := make(chan error, 1)
go func() { done <- Serve(ctx, New("", h, t.Context()), ln, 50*time.Millisecond) }()
go func() {
if resp, err := http.Get("http://" + ln.Addr().String()); err == nil {
resp.Body.Close()
}
}()
<-started
stop()
if err := <-done; err != context.DeadlineExceeded {
t.Fatalf("got %v, want context.DeadlineExceeded", err)
}
}
func TestErrServerClosedAfterShutdown(t *testing.T) {
srv := New("127.0.0.1:0", http.NotFoundHandler(), t.Context())
_ = srv.Shutdown(t.Context())
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
t.Fatalf("got %v", err)
}
}Streaming and connection control: http.ResponseController, Flusher, SSE basics, Hijacker Important
In plain words: Normally the server buffers your output. To send bytes now (progress, Server-Sent Events, NDJSON), call Flush. http.ResponseController (Go 1.20) gives every such control in one place: Flush, SetReadDeadline, SetWriteDeadline, Hijack, and since Go 1.21 EnableFullDuplex. SSE is plain HTTP: Content-Type: text/event-stream and blocks of field: value lines ending in a blank line.
Common misunderstanding: "w.(http.Flusher) always works." Middleware that wraps ResponseWriter hides the interface, and the type assertion fails. NewResponseController looks through wrappers that implement Unwrap() http.ResponseWriter and returns an error matching http.ErrNotSupported otherwise. And "flushed means delivered": the Flusher doc warns that "if the client is connected through an HTTP proxy, the buffered data may not reach the client until the response completes" (nginx buffers unless X-Accel-Buffering: no or proxy_buffering off).
Definition: NewResponseController(rw) "The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter." SetWriteDeadline "sets the deadline for writing the response. Writes to the response body after the deadline has been exceeded will not block, but may succeed if the data has been buffered." EnableFullDuplex: "For HTTP/1 requests, the Go HTTP server by default consumes any unread portion of the request body before beginning to write the response". Hijacker: "The default [ResponseWriter] for HTTP/1.x connections supports Hijacker, but HTTP/2 connections intentionally do not." After a hijack the server forgets the connection (not tracked by Shutdown). The keyword for the write-deadline trick is http.NewResponseController SetWriteDeadline: it overrides Server.WriteTimeout for one response. The doc adds "Setting the write deadline after it has been exceeded will not extend it", and over HTTP/2 that is enforced (the tests show a stream whose first event comes after WriteTimeout delivers nothing if the deadline is set only when the event arrives). So the snippet clears the deadline (SetWriteDeadline(time.Time{})) before it starts waiting, sets now+perWrite just before each event write, clears it again while idle, and ends the stream when SetWriteDeadline returns an error (ErrNotSupported behind a wrapper without Unwrap). SSE needs MIME type text/event-stream; MDN: "Each notification is sent as a block of text terminated by a pair of newlines."
Server.WriteTimeout = 60ms; three events 40 ms apart (real test)
without SetWriteDeadline:
1 t=0 headers flushed
2 t=40 id: 1 written
3 t=60 WriteTimeout deadline passes
4 t=80 write of id: 2 fails, connection closed -> client got fewer than 3 events
with SetWriteDeadline(zero) at start, now+perWrite around each write, zero while idle:
5 t=40,80,120 id: 1, 2, 3 delivered; stream ends cleanly
6 first event at t=100 (> WriteTimeout), HTTP/1.1 and HTTP/2: all 3 delivered
7 gaps of 80 ms with perWrite 30 ms: all 3 delivered (perWrite bounds a write, not idle time)Real scenario: live order-status updates to a browser with EventSource; a log tail endpoint; progress of a long export; a WebSocket library (gorilla/websocket, coder/websocket) that hijacks the HTTP/1.1 connection; an LLM proxy streaming tokens as SSE. Choosing SSE vs WebSockets vs long polling is in Real-Time Communication.
| Need | API | HTTP/1.1 | HTTP/2 |
|---|---|---|---|
| Push bytes now | rc.Flush() / Flusher | Yes | Yes |
| Per-response write deadline | rc.SetWriteDeadline(t) | Yes | Yes |
| Per-request read deadline (uploads) | rc.SetReadDeadline(t) | Yes | Yes |
| Read body while writing | rc.EnableFullDuplex() (Go 1.21) | Opt-in | Always |
| Take over the TCP connection | rc.Hijack() / Hijacker | Yes | No (ErrNotSupported) |
Through TimeoutHandler | n/a | No Flusher/Hijacker | No |
| Through your middleware | Implement Unwrap() | Needed | Needed |
Fix / how to use it:
// Package stream sends Server-Sent Events with http.ResponseController.
// A server-wide WriteTimeout is an absolute deadline that would cut a
// long-lived stream, and an expired deadline cannot be extended, so the
// handler clears it before it starts waiting, bounds each write with its
// own deadline, and clears it again while it waits for the next event.
package stream
import (
"fmt"
"log/slog"
"net/http"
"time"
)
// Event is one SSE message.
type Event struct {
ID int
Name string
Data string
}
// SSE streams events from src until it closes or the client goes away.
// perWrite bounds one event write; 0 keeps Server.WriteTimeout (to show
// what that does to a stream).
func SSE(src func() <-chan Event, perWrite time.Duration) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
rc := http.NewResponseController(w)
setDeadline := func(t time.Time) bool {
if perWrite == 0 {
return true
}
if err := rc.SetWriteDeadline(t); err != nil { // ErrNotSupported behind a wrapper without Unwrap
slog.WarnContext(r.Context(), "sse: cannot set write deadline", "err", err)
return false
}
return true
}
// Clear the server's deadline now, before it can expire while we wait.
if !setDeadline(time.Time{}) {
http.Error(w, "streaming not supported", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.WriteHeader(http.StatusOK)
if err := rc.Flush(); err != nil {
return
}
events := src()
for {
select {
case <-r.Context().Done():
return
case ev, ok := <-events:
if !ok {
return
}
if !setDeadline(time.Now().Add(perWrite)) { // bound this write only
return
}
if _, err := fmt.Fprintf(w, "id: %d\nevent: %s\ndata: %s\n\n", ev.ID, ev.Name, ev.Data); err != nil {
return
}
if err := rc.Flush(); err != nil {
return
}
if !setDeadline(time.Time{}) { // no deadline while idle
return
}
}
}
}
}package stream
import (
"bufio"
"net/http/httptest"
"strings"
"testing"
"time"
)
// source sends three events; gaps[i] is the wait before event i+1.
func source(gaps ...time.Duration) func() <-chan Event {
return func() <-chan Event {
ch := make(chan Event)
go func() {
defer close(ch)
for i, g := range gaps {
time.Sleep(g)
ch <- Event{ID: i + 1, Name: "price", Data: `{"sku":"A1"}`}
}
}()
return ch
}
}
func readIDs(t *testing.T, perWrite time.Duration, gaps ...time.Duration) []string {
return readIDsProto(t, false, perWrite, gaps...)
}
// readIDsProto runs the stream over HTTP/1.1 or, with h2, over HTTP/2 + TLS,
// where an expired write deadline cannot be extended.
func readIDsProto(t *testing.T, h2 bool, perWrite time.Duration, gaps ...time.Duration) []string {
srv := httptest.NewUnstartedServer(SSE(source(gaps...), perWrite))
srv.Config.WriteTimeout = 60 * time.Millisecond
if h2 {
srv.EnableHTTP2 = true
srv.StartTLS()
} else {
srv.Start()
}
defer srv.Close()
resp, err := srv.Client().Get(srv.URL)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if h2 && resp.ProtoMajor != 2 {
t.Fatalf("proto %s", resp.Proto)
}
if ct := resp.Header.Get("Content-Type"); ct != "text/event-stream" {
t.Fatalf("content type %q", ct)
}
var ids []string
sc := bufio.NewScanner(resp.Body)
for sc.Scan() {
if v, ok := strings.CutPrefix(sc.Text(), "id: "); ok {
ids = append(ids, v)
}
}
return ids
}
const ms = time.Millisecond
func TestSSEOutlivesWriteTimeout(t *testing.T) {
if ids := readIDs(t, time.Second, 40*ms, 40*ms, 40*ms); strings.Join(ids, ",") != "1,2,3" {
t.Fatalf("got ids %v", ids)
}
}
func TestSSEFirstEventLaterThanWriteTimeout(t *testing.T) {
// The server-wide deadline (60 ms) passes before the first event (100 ms).
if ids := readIDs(t, time.Second, 100*ms, 10*ms, 10*ms); strings.Join(ids, ",") != "1,2,3" {
t.Fatalf("got ids %v", ids)
}
}
func TestSSEGapLongerThanPerWriteDeadline(t *testing.T) {
// perWrite bounds one write, not the idle time between events.
if ids := readIDs(t, 30*ms, 10*ms, 80*ms, 80*ms); strings.Join(ids, ",") != "1,2,3" {
t.Fatalf("got ids %v", ids)
}
}
func TestWriteTimeoutCutsStreamWithoutPerWriteDeadline(t *testing.T) {
if ids := readIDs(t, 0, 40*ms, 40*ms, 40*ms); len(ids) >= 3 {
t.Fatalf("got all ids %v: WriteTimeout should have cut the stream", ids)
}
}
func TestSSEOverHTTP2FirstEventLaterThanWriteTimeout(t *testing.T) {
if ids := readIDsProto(t, true, time.Second, 100*ms, 10*ms, 10*ms); strings.Join(ids, ",") != "1,2,3" {
t.Fatalf("got ids %v", ids)
}
}
func TestSSEOverHTTP2GapLongerThanPerWriteDeadline(t *testing.T) {
if ids := readIDsProto(t, true, 30*ms, 10*ms, 80*ms, 80*ms); strings.Join(ids, ",") != "1,2,3" {
t.Fatalf("got ids %v", ids)
}
}The client and its Transport: connection pooling and keep-alive Must-know
In plain words: http.Client is the convenience layer (timeouts, redirects, cookies); http.Transport does the work: dialing, TLS, HTTP/2, and a pool of idle keep-alive connections per host. Make one client per upstream (or one for the process), share it between goroutines, and never create one per request.
Common misunderstanding: "A new client per request is harmless" and its mirror "any new client loses the pool". A zero-value &http.Client{} has a nil Transport, and the doc says "If nil, DefaultTransport is used", so many such clients still share one pool (and its defaults: no Client.Timeout, 2 idle conns per host). What destroys reuse is a new Transport per request (often hidden inside a helper that builds &http.Client{Transport: &http.Transport{...}} on every call), which means a new TCP and TLS handshake every time, thousands of sockets in TIME_WAIT, and eventually "cannot assign requested address" (ephemeral port exhaustion, see Ports, Sockets & Connections). The doc: "Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines." Same for Transport: "Transports should be reused instead of created as needed."
Definition: DefaultTransport sets Proxy: ProxyFromEnvironment, a dialer with 30 s connect timeout and 30 s TCP keep-alive, ForceAttemptHTTP2: true, MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second. DefaultMaxIdleConnsPerHost = 2. MaxIdleConnsPerHost, "if non-zero, controls the maximum idle (keep-alive) connections to keep per-host"; MaxConnsPerHost "optionally limits the total number of connections per host ... On limit violation, dials will block." DisableKeepAlives "is unrelated to the similarly named TCP keep-alives". HTTP/2 default: over TLS the transport negotiates h2 via ALPN; a custom DialContext, DialTLSContext or TLSClientConfig turns that off unless ForceAttemptHTTP2 is true. Since Go 1.24, Transport.Protocols selects HTTP/1, HTTP/2 and unencrypted HTTP/2 explicitly.
100 concurrent requests to one host, MaxIdleConnsPerHost = 2 (default)
1 100 conns dialed (no limit: MaxConnsPerHost = 0)
2 all finish; pool keeps 2 idle, closes 98 -> 98 sockets in TIME_WAIT on this side
3 next burst: 98 new handshakes again
with MaxIdleConnsPerHost = 32, MaxConnsPerHost = 64
4 at most 64 in flight, the rest wait for a free conn; 32 stay warm between bursts
over HTTP/2: one TCP connection carries many streams; per-host limits mostly stop matteringReal scenario: a service calling a payment provider 500 times a second; a fan-out to one internal API from many goroutines; a crawler hitting thousands of hosts (where MaxIdleConns and IdleConnTimeout keep the pool from holding thousands of idle sockets); a client behind a corporate proxy configured with HTTPS_PROXY.
| Field | Default (DefaultTransport or zero value) | Meaning |
|---|---|---|
MaxIdleConns | 100 (zero value: no limit) | Idle conns across all hosts |
MaxIdleConnsPerHost | 2 | Idle conns kept per host |
MaxConnsPerHost | 0 (no limit) | Dialing + active + idle per host |
IdleConnTimeout | 90 s (zero value: no limit) | Close idle conns after |
DisableKeepAlives | false | One request per connection |
ForceAttemptHTTP2 | true | Keep HTTP/2 with custom dialers |
DisableCompression | false | Transport asks for gzip and decodes it |
Proxy | ProxyFromEnvironment | HTTP_PROXY, HTTPS_PROXY, NO_PROXY |
Fix / how to use it: a constructor that returns a tuned client, used by the whole process:
// Package client builds one reusable http.Client with a tuned Transport
// and a GetJSON helper that bounds every request with a context, checks
// the status, limits and closes the body, and lets the connection be reused.
package client
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"time"
)
// New returns a client for one upstream. Create it once and share it:
// the Transport holds the connection pool.
func New() *http.Client {
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 2 * time.Second, // TCP connect
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: true, // custom DialContext/TLSClientConfig would otherwise disable h2
MaxIdleConns: 200,
MaxIdleConnsPerHost: 32, // default is 2: too low for a busy upstream
MaxConnsPerHost: 64, // 0 = unlimited
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 3 * time.Second,
ResponseHeaderTimeout: 5 * time.Second,
ExpectContinueTimeout: time.Second,
}
return &http.Client{
Transport: tr,
Timeout: 10 * time.Second, // backstop; per-call budgets come from ctx
}
}
// StatusError is returned for non-2xx responses.
type StatusError struct {
Code int
Body string
}
func (e *StatusError) Error() string { return fmt.Sprintf("upstream status %d: %s", e.Code, e.Body) }
// GetJSON fetches url into dst under ctx.
func GetJSON(ctx context.Context, c *http.Client, url string, dst any) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
return err // *url.Error; errors.Is(err, context.DeadlineExceeded) works
}
defer func() {
// Drain a bounded remainder and close, so the connection goes back to the pool.
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 64<<10))
resp.Body.Close()
}()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
b, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return &StatusError{Code: resp.StatusCode, Body: string(b)}
}
return json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(dst)
}Client timeouts and context with NewRequestWithContext Must-know
In plain words: Give every outgoing request the caller's context with http.NewRequestWithContext(ctx, ...) and a derived per-call budget. Keep Client.Timeout as a generous backstop, and set ResponseHeaderTimeout and the dial and TLS timeouts on the Transport.
Common misunderstanding: "Client.Timeout only covers getting the response." It covers the whole exchange including reading the body: "The timer remains running after Get, Head, Post, or Do return and will interrupt reading of the Response.Body." A 10 s timeout on a client that downloads a 2 GB file fails mid-download. The context budget has the same reach, and it also knows the caller's deadline; the details of context propagation are in context: Client side.
Definition: "Timeout specifies a time limit for requests made by this Client. The timeout includes connection time, any redirects, and reading the response body." "A Timeout of zero means no timeout." On the Transport: net.Dialer.Timeout bounds the TCP connect, TLSHandshakeTimeout the handshake, ResponseHeaderTimeout "the amount of time to wait for a server's response headers after fully writing the request", ExpectContinueTimeout the wait for 100 Continue. Errors come back as *url.Error; errors.Is(err, context.DeadlineExceeded) works for ctx deadlines, and Client.Timeout produces (Client.Timeout exceeded while awaiting headers) with Timeout() == true.
budget: handler has 2s left; GetJSON gets WithTimeout(ctx, 300ms)
1 t=0 dial (Dialer.Timeout 2s, but ctx says 300ms)
2 t=12 TLS (TLSHandshakeTimeout 3s)
3 t=20 request written; ResponseHeaderTimeout 5s starts
4 t=300 ctx deadline: dial/TLS/headers/body aborted, conn discarded
5 err: Get "http://.../reviews?user=1": context deadline exceeded -> handler answers 504Real scenario: a checkout that calls fraud, tax and payment services, each with its own budget inside the request's; a health checker that must answer in 1 s; a webhook sender that retries with backoff (retry policy and jitter: Timeouts, Retries & Jitter); a file download where only connect and header timeouts apply and the body has none.
| Timeout | Covers | Default | Knows caller's deadline |
|---|---|---|---|
ctx from NewRequestWithContext | Everything, including body | none | Yes |
Client.Timeout | Everything incl. redirects and body | 0 | No |
net.Dialer.Timeout | TCP connect | 30 s in DefaultTransport | Through ctx |
Transport.TLSHandshakeTimeout | TLS handshake | 10 s in DefaultTransport | No |
Transport.ResponseHeaderTimeout | Wait for headers | 0 | No |
Transport.ExpectContinueTimeout | Wait for 100 Continue | 1 s in DefaultTransport | No |
Transport.IdleConnTimeout | Idle pooled conn lifetime | 90 s | n/a |
Fix / how to use it: the client tests prove the deadline: a 50 ms ctx against a handler that waits 1 s returns an error for which errors.Is(err, context.DeadlineExceeded) is true.
package client
import (
"context"
"errors"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
// countingServer counts new TCP connections the server accepts.
func countingServer(t *testing.T, h http.HandlerFunc) (*httptest.Server, *atomic.Int32) {
var conns atomic.Int32
srv := httptest.NewUnstartedServer(h)
srv.Config.ConnState = func(_ net.Conn, s http.ConnState) {
if s == http.StateNew {
conns.Add(1)
}
}
srv.Start()
t.Cleanup(srv.Close)
return srv, &conns
}
func TestGetJSONReusesOneConnection(t *testing.T) {
srv, conns := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, `{"name":"pen"}`+strings.Repeat(" ", 8<<10)) // trailing data after the value
})
c := New()
for range 10 {
var v struct{ Name string }
if err := GetJSON(t.Context(), c, srv.URL, &v); err != nil || v.Name != "pen" {
t.Fatalf("%+v %v", v, err)
}
}
if n := conns.Load(); n != 1 {
t.Fatalf("10 sequential requests used %d connections, want 1", n)
}
}
func TestBodyNotClosedLeaksConnections(t *testing.T) {
big := strings.Repeat("x", 256<<10)
srv, conns := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
_, _ = io.WriteString(w, big)
})
c := New()
for range 5 {
resp, err := c.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
_ = resp // bug on purpose: Body neither read nor closed
}
if n := conns.Load(); n != 5 {
t.Fatalf("got %d connections, want 5 (one per unclosed body)", n)
}
}
func TestContextDeadlineBoundsTheCall(t *testing.T) {
srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(time.Second):
case <-r.Context().Done():
}
})
ctx, cancel := context.WithTimeout(t.Context(), 50*time.Millisecond)
defer cancel()
var v any
err := GetJSON(ctx, New(), srv.URL, &v)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("got %v", err)
}
}
func TestNon2xxIsAnError(t *testing.T) {
srv, _ := countingServer(t, func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "upstream down", http.StatusBadGateway)
})
var v any
err := GetJSON(t.Context(), New(), srv.URL, &v)
var se *StatusError
if !errors.As(err, &se) || se.Code != http.StatusBadGateway {
t.Fatalf("got %v", err)
}
}Response bodies: close and drain Must-know
In plain words: After Do returns without error you own resp.Body. Close it, always, even when you do not need it and even for a 404. If you stop reading early, read and discard a bounded rest before closing so the connection can be reused. This is the "response body close and drain" rule.
Common misunderstanding: "If err != nil, resp is nil": almost, but the Do doc says "A non-nil Response with a non-nil error only occurs when CheckRedirect fails, and even then the returned [Response.Body] is already closed", so on error you never close the body and you ignore resp (unless you need it from a CheckRedirect failure); and "a non-2xx status is an error" (it is not: err == nil, and the body holds the error page). On the other side, "draining is obsolete since Go 1.27": the 1.27 notes say HTTP/1 bodies now drain on close "up to a conservative limit", so closing alone is usually enough, but a large unread remainder still costs a connection, and an unclosed body always does.
Definition: Response.Body doc: "The http Client and Transport guarantee that Body is always non-nil, even on responses without a body or responses with a zero-length body. It is the caller's responsibility to close Body. The default HTTP client's Transport may not reuse HTTP/1.x "keep-alive" TCP connections if the Body is not read to completion and closed". An unclosed body keeps its connection busy and leaks the Transport's reader and writer goroutines for that connection.
5 calls to a 256 KB endpoint, body never closed (real test, Go 1.27.4)
1 call 1: dial conn A; body unread, not closed -> A busy
2 call 2: no idle conn -> dial B ... call 5 -> dial E
3 server saw 5 new connections (ConnState StateNew counted)
10 calls through GetJSON (decode, bounded drain, Close)
4 server saw 1 connection for all 10Real scenario: a monitoring job polling 200 endpoints every 10 s that ran out of file descriptors in a day; a retry loop that skipped Close on the error-status path; a client that returns early after reading the status and leaks one connection per call; goroutine dumps full of net/http.(*persistConn).readLoop.
| Pattern | Connection reused | Leak |
|---|---|---|
defer resp.Body.Close() after the err check, body read to EOF | Yes | No |
Read part, io.Copy(io.Discard, io.LimitReader(body, 64<<10)), Close | Only if that reaches EOF; a larger remainder is closed unread | No |
| Close without reading (Go 1.27+) | If the remainder fits the "conservative limit" of the automatic drain | No |
| Close without reading (before 1.27) | Often no | No |
| Never close | No | Connection + 2 goroutines per call |
defer resp.Body.Close() before checking err | n/a | Panics on nil resp (the usual error case) |
Fix / how to use it: the defer inside GetJSON drains at most 64 KB and closes, on every path, including non-2xx. The bound is deliberate: reading an unknown amount to save one connection can cost more than a new handshake, so a body larger than the drain limit is simply closed and its connection discarded. The Do doc states the rule: "If the Body is not both read to EOF and closed, the [Client]'s underlying [RoundTripper] (typically [Transport]) may not be able to re-use a persistent TCP connection".
http.DefaultClient pitfalls Important
In plain words: http.Get, http.Post and http.Head use http.DefaultClient, a client with no timeout over DefaultTransport. Fine for a script; wrong for a server.
Common misunderstanding: "Setting http.DefaultClient.Timeout = 5 * time.Second in main fixes it." It is a shared global: every library in the process that uses http.Get now has your timeout, and a library that changes http.DefaultTransport changes yours. Own your client.
Definition: "DefaultClient is the default [Client] and is used by [Get], [Head], and [Post]." var DefaultClient = &Client{}: zero Timeout, nil Transport meaning DefaultTransport. Cloudflare's guide: "the package level functions such as http.Get use a Client without timeouts, so are dangerous to use on the open Internet."
1 handler calls http.Get(upstream) no ctx, no timeout
2 upstream accepts TCP, never answers
3 handler goroutine blocked forever; client of this service times out and retries
4 retries pile up; goroutines grow without bound -> OOMReal scenario: the Before FetchProfile; an SDK that defaults to http.DefaultClient and accepts an *http.Client option you forgot to pass; tests that replace http.DefaultTransport and affect other tests running in parallel.
| Shortcut | Client | Timeout | Context |
|---|---|---|---|
http.Get(url) | DefaultClient | none | Background |
http.Post(url, ct, body) | DefaultClient | none | Background |
http.NewRequest(...) + c.Do | yours | yours | Background |
http.NewRequestWithContext(ctx, ...) + c.Do | yours | yours | caller's |
Fix / how to use it: inject an *http.Client into everything that calls out (App.http in After), and pass it to SDKs that accept one.
Testing with httptest Must-know
In plain words: httptest.NewRecorder() is a fake ResponseWriter for calling a handler directly; httptest.NewRequest builds a server-side request. httptest.NewServer(h) starts a real server on 127.0.0.1 with a random port, for testing clients and anything involving connections, timeouts or streaming.
Common misunderstanding: "A recorder test covers timeouts and streaming." The recorder has no connection: WriteTimeout, keep-alive, Hijack, connection reuse and ErrAbortHandler only show up against NewServer/NewUnstartedServer. Conversely, spinning up a server for every handler unit test is slower than needed.
Definition: NewRecorder returns an *httptest.ResponseRecorder with Code, Body and Header(); NewRequest(method, target, body) panics on a bad target and sets RemoteAddr to 192.0.2.1:1234. NewServer serves on a loopback listener; NewUnstartedServer lets you change srv.Config (timeouts, ConnState, ErrorLog) before Start; NewTLSServer adds a self-signed certificate and srv.Client() trusts it. Since Go 1.26 that client "will now redirect requests for example.com and any subdomains to the server being tested". Go 1.27 adds httptest.NewTestServer for testing/synctest (not used here, the module is go 1.24).
unit (recorder) integration (real server)
1 rec := httptest.NewRecorder() srv := httptest.NewUnstartedServer(h)
2 h.ServeHTTP(rec, NewRequest(...)) srv.Config.WriteTimeout = 60ms; srv.Start()
3 assert rec.Code, rec.Body resp, _ := srv.Client().Get(srv.URL)
4 µs per case, no sockets real TCP, timeouts, keep-alive, ConnStateReal scenario: table-driven tests of every route's status code (TestCRUDStatusCodes); a client library tested against a fake upstream that returns 500 or hangs; a test counting TCP connections with ConnState to prove pooling; TLS-only cookie behaviour tested with NewTLSServer and a cookie jar.
| Tool | Gives you | Use for |
|---|---|---|
httptest.NewRecorder() | In-memory ResponseWriter | Handlers, routing, status codes |
httptest.NewRequest | Server-side *Request | Recorder tests |
httptest.NewRequestWithContext (1.23) | Same with a ctx | Canceled-client tests |
httptest.NewServer(h) | Real HTTP server on loopback | Clients, timeouts, streaming |
httptest.NewUnstartedServer(h) | Configure srv.Config first | ConnState, WriteTimeout, ErrorLog |
httptest.NewTLSServer(h) | HTTPS + trusting srv.Client() | Secure cookies, HTTP/2 |
net/http/httptrace | Hooks: GotConn, DNSDone, WroteRequest | Measuring reuse and latency phases |
Fix / how to use it: every package of this chapter's module is tested this way; the testing package in general is in Testing & Benchmarking and fakes for dependencies in Mocking with Interfaces.
http.CrossOriginProtection (1.25) Good to know
In plain words: Go 1.25 added a CSRF guard to the standard library: wrap your mux and non-safe cross-origin browser requests (a POST from another site) get 403, with no tokens and no cookies, using the browser's Sec-Fetch-Site and Origin headers.
Common misunderstanding: "It replaces CORS." CORS decides what a page from another origin may read; CSRF protection decides whether a cross-site request may change state. And "GET is protected too": safe methods are always allowed, so GET handlers must never change state.
Definition: from csrf.go: "CrossOriginProtection implements protections against [Cross-Site Request Forgery (CSRF)] by rejecting non-safe cross-origin browser requests." "Cross-origin requests are currently detected with the [Sec-Fetch-Site] header, available in all browsers since 2023, or by comparing the hostname of the [Origin] header with the Host header." "Requests without Sec-Fetch-Site or Origin headers are currently assumed to be either same-origin or non-browser requests, and are allowed." Methods: AddTrustedOrigin, AddInsecureBypassPattern, SetDenyHandler, Check, Handler. Not compiled here: it needs go 1.25 in go.mod.
// Go 1.25+ (not in the snippet module, which says go 1.24)
cop := http.NewCrossOriginProtection()
if err := cop.AddTrustedOrigin("https://admin.example.test"); err != nil {
log.Fatal(err)
}
cop.AddInsecureBypassPattern("POST /webhooks/{provider}") // server-to-server, signed instead
srv := &http.Server{Handler: cop.Handler(mux), ReadHeaderTimeout: 5 * time.Second}1 evil.example sends a form POST to https://shop.example.test/orders
2 browser adds Sec-Fetch-Site: cross-site
3 CrossOriginProtection: non-safe method + cross-site -> 403 Forbidden
4 same request from shop.example.test: Sec-Fetch-Site: same-origin -> allowedReal scenario: a server-rendered admin panel with cookie sessions; a JSON API that also accepts cookie auth from the SPA; webhook endpoints that must bypass the check (they are authenticated by signatures). Token-based CSRF and the rest of the auth story: Authentication in Go.
| Header | Value | Decision |
|---|---|---|
Sec-Fetch-Site | same-origin, none | Allow |
Sec-Fetch-Site | cross-site, same-site | Reject non-safe methods |
no Sec-Fetch-Site, Origin host == Host | n/a | Allow |
| neither header | n/a | Allow (non-browser client) |
| Trusted origin / bypass pattern | configured | Allow |
Routers and frameworks: http.ServeMux vs chi/gin/echo Important
In plain words: Since Go 1.22, ServeMux covers method, host and wildcard routing with precise precedence. chi adds route groups, sub-routers, regex segments and a middleware toolkit, and stays net/http-compatible. gin and echo are frameworks with their own context type and handler signature.
Common misunderstanding: "gin is faster, so it is better for production." Router speed is rarely the bottleneck; Alex Edwards: "Unless you have profiling that confirms your router is a bottleneck in your application, I recommend choosing between them based on the specific features that you need rather than performance." His rule: "If you can use http.ServeMux, you probably should." The real cost of gin and echo is that handlers are func(*gin.Context) / func(*echo.Context) error (echo v5), so standard middleware and handlers need adapters.
Definition: chi's README: "a lightweight, idiomatic and composable router for building Go HTTP services" and "100% compatible with net/http". gin's README: "It provides a Martini-like API but with significantly better performance—up to 40 times faster—thanks to httprouter." echo: "High performance, extensible, minimalist Go web framework." Alex Edwards (May 2025): chi "is the only shortlisted router to support more than one wildcard within a single URL path segment"; with ServeMux "a 'catch all' route "/" ... will inhibit the automatic sending of 405 responses".
choose a router
1 methods + {id} + host + subtree only? -> http.ServeMux
2 route groups with their own middleware? -> chi (or wrap ServeMux by hand)
3 regex segments, {month}-{year} in one segment? -> chi or gorilla/mux
4 team wants binding, validation, rendering built in and accepts lock-in -> gin / echoReal scenario: a new internal service started on ServeMux and never needed more; a 200-route public API with versioned groups on chi; a legacy gin codebase where new handlers are written as http.Handler and wrapped with gin.WrapH; a team that switched from gorilla/mux (first-match-wins) and had to reorder nothing because ServeMux ignores order.
| Feature | http.ServeMux (1.22+) | chi | gin | echo |
|---|---|---|---|---|
| Handler type | http.Handler | http.Handler | func(*gin.Context) | func(*echo.Context) error (v5) |
| Method matching | Yes | Yes | Yes | Yes |
| Path params | {id}, {rest...}, {$} | {id}, {slug:[a-z-]+}, * | :id, *rest | :id, * |
| Precedence | Most specific; conflicts panic | Static before param | Tree (httprouter-style) | Static, param, any |
| Host matching | Yes | Via hostrouter | No host API in gin.go | No Host method in v5 echo.go |
| Automatic 405 | Yes, with Allow | Yes (Allow may duplicate, per Alex Edwards) | Off: HandleMethodNotAllowed: false default | Router has a MethodNotAllowedHandler |
| Route groups / sub-routers | Manual (StripPrefix, wrap) | Yes | Yes | Yes |
| Binding / validation | No | No | Yes | Yes |
| Std middleware works unchanged | Yes | Yes | Adapter | Adapter |
| Dependency | none | small | larger | larger |
Mechanics
The accept loop and one goroutine per connection Important
Server.Serve(l) "accepts incoming connections on the Listener l, creating a new service goroutine for each. The service goroutines read requests and then call s.Handler to reply to them." In the source this is a for loop around l.Accept() ending in go c.serve(connCtx). Temporary accept errors (for example EMFILE, too many open files) are retried with a backoff from 5 ms doubling to 1 s, and logged as http: Accept error: ...; retrying in ....
1 ln := net.Listen("tcp", ":8080") ListenAndServe does this
2 for { rw := ln.Accept() blocks
3 c := srv.newConn(rw); connCtx := ConnContext(BaseContext(ln), rw)
4 go c.serve(connCtx) } one goroutine per TCP connection
5 c.serve: TLS handshake (if any) -> ALPN "h2"? hand over to HTTP/2 server
6 HTTP/1.1 loop: readRequest (ReadHeaderTimeout) -> ServeHTTP -> finishRequest
7 -> keep-alive? wait for next request (IdleTimeout) : close
8 HTTP/2: one serve goroutine per conn + `go sc.runHandler(...)` per stream (internal/http2/server.go)For HTTP/1.1 the server reads requests on a connection one at a time (no pipelining in parallel), and while the handler runs it keeps a background read on the socket so that a closed connection cancels r.Context(). For HTTP/2 each stream runs its handler in its own goroutine, so one connection can serve many requests concurrently, which is why per-host connection limits matter much less over h2.
How ServeMux matches: a decision tree Good to know
Since Go 1.22, patterns are parsed (pattern.go) into a host, a method and segments, and stored in a decision tree (routing_tree.go): "The root of the tree branches on the host of the request. The next level branches on the method. The remaining levels branch on consecutive segments of the path." Literal children are tried before wildcard children, and because of the precedence rule the search can backtrack: given /a/b/z and /a/{x}/c, the path /a/b/c first tries /a/b/z and then falls back to /a/{x}/c. Conflicts are found at registration, where the new pattern is compared with every pattern it could overlap (the panic message explains the overlap with two example paths, as in the routing test). The mux also cleans the path (removing ., .. and double slashes) and redirects with 307 before matching, and answers 405 when the path matched under some method but not this one.
host "" ──▶ method "GET" ──▶ "posts" ──▶ "latest" (leaf: GET /posts/latest)
└──▶ {id} (leaf: GET /posts/{id})
──▶ method "POST" ──▶ "posts" (leaf: POST /posts)
──▶ method "" ──▶ "static" ──▶ {...} (leaf: /static/, any method)
host "api.example.test" ──▶ method "" ──▶ "version"The client: Do, RoundTrip, the idle pool Important
Client.Do handles redirects, cookies and Client.Timeout, then calls Transport.RoundTrip. getConn looks in the idle pool for a connection to the same connectMethod (scheme, host, proxy); if none is idle it dials, unless MaxConnsPerHost is reached, in which case it waits. Each HTTP/1 connection (persistConn) has a readLoop and a writeLoop goroutine. When the response body reaches EOF or is closed (and, since 1.27, drained within the limit), readLoop calls tryPutIdleConn, which keeps the connection only if the per-host and total idle limits allow it. An HTTP/2 connection is shared by many concurrent requests and is returned to the pool immediately.
1 c.Do(req) -> send(req, deadline) -> t.RoundTrip(req)
2 t.getConn: idle conn for https://api.example.test:443? yes -> reuse (httptrace GotConnInfo.Reused = true)
3 no -> dial + TLS (+ ALPN h2)
4 pc.writeLoop writes the request; pc.readLoop reads the response headers
5 caller reads resp.Body ... EOF or Close
6 readLoop: tryPutIdleConn(pc) -> idle list (≤ MaxIdleConnsPerHost) or closeExact errors and log lines Must-know
| Text | Where it comes from |
|---|---|
http: Server closed | http.ErrServerClosed, returned by Serve/ListenAndServe after Shutdown or Close |
http: request body too large | *http.MaxBytesError from MaxBytesReader |
http: Handler timeout | http.ErrHandlerTimeout, writes after TimeoutHandler fired |
http: superfluous response.WriteHeader call from ... | Server log: second WriteHeader |
http: Accept error: ...; retrying in ... | Server log: temporary accept error (e.g. too many open files) |
404 page not found | http.NotFound / ServeMux |
Method Not Allowed | ServeMux 405 body (http.StatusText), with Allow header |
431 Request Header Fields Too Large | Server: headers over MaxHeaderBytes |
pattern "..." conflicts with pattern "..." | Panic in ServeMux.Handle at registration |
Get "http://...": context deadline exceeded | *url.Error wrapping the ctx error |
... (Client.Timeout exceeded while awaiting headers) | Client.Timeout fired |
net/http: request canceled while waiting for connection | ctx ended while waiting for a pooled conn or MaxConnsPerHost slot |
stopped after 10 redirects | Default CheckRedirect |
http: no such file / http: named cookie not present | ErrMissingFile / ErrNoCookie |
feature not supported | http.ErrNotSupported from ResponseController |
Solving the classic problems
| Bug | Symptom | Fix | Cost |
|---|---|---|---|
http.ListenAndServe with no timeouts | fd and goroutine growth, slowloris | http.Server with the four timeouts | 6 lines |
Routes on DefaultServeMux | Unexpected /debug/pprof/ in production | http.NewServeMux() | None |
| Prefix route parsed by hand | Wrong method served, 7/orders read as an id | GET /users/{id} + PathValue | None |
Catch-all / for custom 404 | 405 becomes 404 | Wrap the mux, rewrite 404 bodies | Small wrapper |
| No body limit | Memory spike on large POST | MaxBytesReader per route | One line |
| Lenient JSON decode | Typos accepted, trailing junk accepted | DisallowUnknownFields + second Decode | Helper |
http.Error without return | superfluous WriteHeader, mixed body | return after every error write | Discipline |
Headers after WriteHeader | Wrong Content-Type | Set headers first | None |
New http.Transport per call (often inside a per-call client) | TIME_WAIT, port exhaustion | One shared client with one Transport | Wiring |
| Unclosed bodies | Connection and goroutine leak | defer resp.Body.Close() after err check | None |
http.Get in a server | Hung goroutines on a slow upstream | Own client + NewRequestWithContext | Wiring |
log.Fatal(srv.ListenAndServe()) | Dropped requests on deploy | Shutdown + wait | 20 lines |
Global WriteTimeout on streams | SSE cut after N seconds | Per-write SetWriteDeadline | One call per event |
Slow clients and missing timeouts
Construct the server with server.New above; put ReadHeaderTimeout first, because it closes the slowloris door without limiting legitimate slow uploads, and set IdleTimeout below the idle timeout of the load balancer in front of you (or above it if the LB initiates idle closes; what matters is that the side that closes first is the one that never reuses). A reverse proxy (nginx, Envoy) in front adds its own limits but does not replace these: internal callers bypass it.
Connection churn on the client
Symptoms: thousands of TIME_WAIT sockets (ss -tan state time-wait | wc -l), latency spikes from TLS handshakes, and dial errors under load. Causes, in order of frequency: a new Transport per request (a zero-value &http.Client{} alone still shares DefaultTransport), unclosed bodies, and MaxIdleConnsPerHost left at 2 for a host that gets hundreds of concurrent calls. The fixes are the client.New constructor and the close-and-drain defer in GetJSON; the measurement is httptrace.ClientTrace.GotConn (Reused) or the server's ConnState, as the client tests do.
Upstream errors mapped to the right status
The userReviews handler in After is the pattern: a per-call budget from r.Context(), context.DeadlineExceeded → 504, a non-2xx StatusError → 502, context.Canceled → write nothing (the client left), any other transport error → 502. Classifying context errors for logs and retries is in context: Classify errors.
Request size and shape
Every handler that reads a body applies three limits: bytes (MaxBytesReader), shape (strict decode, one value, known fields) and content (business validation → 422). Query parameters get typed parsing with whitelists. The order matters for status codes: 415, 413, 400, 422.
Choosing
| Situation | Use | Extra technique | Reason |
|---|---|---|---|
| New JSON API | http.NewServeMux + Go 1.22 patterns | jsonio-style helpers | No dependency, precise precedence |
| Need route groups with middleware | chi | Or StripPrefix + wrapped sub-mux | Grouping without lock-in |
| Regex path segments | chi or gorilla/mux | Validate in handler otherwise | ServeMux has no regex |
| Home page | GET /{$} | Never bare / | / matches everything |
| Custom 404 page | Wrapper around the mux | Keep mux's 405 | Catch-all hides 405 |
| Any public server | http.Server with all timeouts | MaxHeaderBytes | Slow clients |
| Large uploads | ReadHeaderTimeout + per-route SetReadDeadline | MaxBytesReader, multipart to disk | Global ReadTimeout too blunt |
| SSE / streaming | ResponseController Flush + SetWriteDeadline | No TimeoutHandler | Long-lived responses |
| Hard handler budget, untrusted code | http.TimeoutHandler | ctx-aware handler | Guaranteed 503 |
| Outgoing calls | One http.Client per upstream | NewRequestWithContext per call | Pooling + budgets |
| Many concurrent calls to one host | MaxIdleConnsPerHost ≈ concurrency | HTTP/2 if the upstream supports it | Default of 2 churns |
| Static assets in one binary | embed + FileServerFS + StripPrefix | Fingerprinted names, long cache | No file deploys |
| Cookie-session forms (Go 1.25+) | http.CrossOriginProtection | SameSite=Lax cookies | Stdlib CSRF defence |
| Deploys without dropped requests | Shutdown with grace < kill timer | Fail readiness first | Rolling updates |
| Tests | httptest.NewRecorder for handlers, NewServer for clients | ConnState, httptrace | Fast vs realistic |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One binary, one http.Server, one ServeMux with every route visible in a single Routes() function, handlers as methods on an App struct holding the *sql.DB, the logger and one *http.Client per external provider. Static assets are embedded; main wires signal.NotifyContext → server.Serve with a 20 s grace → close the DB pool. Example: an online shop where GET /products, POST /cart/items, POST /checkout and the admin pages live in one process behind nginx; the only outgoing HTTP is the payment provider, called with a 3 s budget inside the 10 s checkout request.
Modular monolith and multiple databases
Each module exposes Register(mux *http.ServeMux) (as static.Register and web.Register do here) or a sub-mux mounted under its prefix with StripPrefix, so module boundaries are visible in the route table and conflicts between modules panic at startup. Modules that call each other do so in-process, not over HTTP; when a module owns a second database (catalog in PostgreSQL, sessions in Redis), its handlers still get the same request context and budgets. Route metrics labelled by r.Pattern show which module is slow without one time series per id.
Microservices
Every service is both a server and a client. On the server side, the same timeouts and shutdown, plus a health endpoint for the orchestrator and readiness that fails before Shutdown starts. On the client side, one pooled client per downstream with explicit budgets and status mapping (504 for slow, 502 for broken). Example flow: POST /orders on the orders service → GET http://inventory/stock/{sku} (200 ms budget) → POST http://payments/charges with an Idempotency-Key header (2 s budget) → 201 with Location. If payments times out, the outcome is unknown: orders answers 504 or 202 and reconciles later, never blindly retries a non-idempotent POST (see API Idempotency). What does not survive the hop: the context object (only a timeout header and trace headers travel), cookies (service-to-service uses tokens), and the guarantee that the callee stopped when you gave up.
Distributed data: replicas, caches, sharded databases, multi-region
HTTP is often the transport to the data layer too: Elasticsearch, object storage, cache APIs, a CDN origin. The same client rules apply with sharper edges: a read from a replica or cache should get a short budget and a fallback; a write over HTTP whose response was lost is an unknown outcome; across regions, connection reuse matters more because each new TLS handshake costs several round trips of 50–150 ms. Responses served from caches and CDNs depend on correct Cache-Control, ETag and Vary headers, which ServeContent and FileServerFS handle for files and you must set yourself for JSON (CDN design: CDNs).
Scaling path: 1×, 10×, 100×
| Load | What changes | net/http practice |
|---|---|---|
| 1× (one instance) | Defaults seem fine | Timeouts, body limits, own mux and client from day one; httptest in CI |
| 10× (several instances behind a load balancer) | Deploys drop requests; connections churn | Graceful shutdown with readiness; MaxIdleConnsPerHost sized; IdleTimeout vs LB idle timeout; route metrics by r.Pattern |
| 100× (many services, high fan-out) | Tail latency, retries amplify load, port exhaustion | HTTP/2 to upstreams that support it, MaxConnsPerHost as a bulkhead, per-call budgets, load shedding at the edge (Load Shedding), streaming instead of buffering large responses |
Lab
1. Run the tests (real)
cd docs/snippets/go/http-server-client/go
gofmt -l . && go vet ./... && go test -race -count=1 ./...
# ok academy/http-server-client/after 1.674s
# ok academy/http-server-client/before 1.380s
# ok academy/http-server-client/client 1.444s
# ? academy/http-server-client/cmd/api [no test files]
# ok academy/http-server-client/jsonio 1.383s
# ok academy/http-server-client/limits 1.397s
# ok academy/http-server-client/params 1.526s
# ok academy/http-server-client/routing 1.344s
# ok academy/http-server-client/server 1.561s
# ok academy/http-server-client/static 1.350s
# ok academy/http-server-client/stream 2.271s
# ok academy/http-server-client/web 1.391s2. Precedence and 405 (real)
go test -run 'TestPatterns|TestCatchAllHides405|TestConflictPanicsAtRegistration' -v ./routing
# --- PASS: TestPatterns (GET /posts/latest beats /posts/{id}; DELETE -> 405 Allow: GET, HEAD)
# --- PASS: TestCatchAllHides405 (with "/" registered the same DELETE is 404)
# --- PASS: TestConflictPanicsAtRegistration (".../{resource}/latest ... neither is more specific than the other")3. Connection reuse vs leak (real)
go test -run 'TestGetJSONReusesOneConnection|TestBodyNotClosedLeaksConnections' -v ./client
# --- PASS: TestGetJSONReusesOneConnection (10 requests, 1 TCP connection)
# --- PASS: TestBodyNotClosedLeaksConnections (5 requests, 5 TCP connections)4. Streaming past WriteTimeout (real)
go test -run 'TestSSE|TestWriteTimeout' -v ./stream
# --- PASS: TestSSEOutlivesWriteTimeout (ids 1,2,3 over 120 ms with WriteTimeout 60 ms)
# --- PASS: TestSSEFirstEventLaterThanWriteTimeout (first event at 100 ms)
# --- PASS: TestSSEGapLongerThanPerWriteDeadline (80 ms gaps, perWrite 30 ms)
# --- PASS: TestWriteTimeoutCutsStreamWithoutPerWriteDeadline
# --- PASS: TestSSEOverHTTP2FirstEventLaterThanWriteTimeout (same over HTTP/2 + TLS)
# --- PASS: TestSSEOverHTTP2GapLongerThanPerWriteDeadline5. Graceful shutdown against a real process (real)
cmd/api in the snippet module wires after.New(...).Routes(), a GET /slow route that takes 3 s, server.New and server.Serve under signal.NotifyContext:
// Command api runs the after service with server timeouts and graceful
// shutdown, plus a /slow route for the shutdown lab.
//
// go run ./cmd/api -addr 127.0.0.1:8080
package main
import (
"context"
"flag"
"io"
"log/slog"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"academy/http-server-client/after"
"academy/http-server-client/server"
)
func main() {
addr := flag.String("addr", "127.0.0.1:8080", "listen address")
reviews := flag.String("reviews", "http://127.0.0.1:9090", "review service base URL")
grace := flag.Duration("grace", 20*time.Second, "shutdown grace period")
flag.Parse()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
mux := http.NewServeMux()
mux.Handle("/", after.New(*reviews).Routes())
mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(3 * time.Second): // in-flight work that shutdown waits for
_, _ = io.WriteString(w, "slow done\n")
case <-r.Context().Done():
}
})
ln, err := net.Listen("tcp", *addr)
if err != nil {
slog.Error("listen", "err", err)
os.Exit(1)
}
slog.Info("listening", "addr", ln.Addr().String(), "pid", os.Getpid())
srv := server.New(*addr, mux, context.Background())
if err := server.Serve(ctx, srv, ln, *grace); err != nil {
slog.Error("shutdown", "err", err)
os.Exit(1)
}
slog.Info("stopped cleanly")
}cd docs/snippets/go/http-server-client/go
go build -o /tmp/api ./cmd/api && /tmp/api -addr 127.0.0.1:18080 & PID=$!; sleep 0.5
curl -s -o /dev/null -w 'slow: %{http_code} after %{time_total}s\n' http://127.0.0.1:18080/slow & sleep 0.5
kill -TERM $PID; wait $PID; echo "exit status $?"
# 2026/11/28 15:52:20 INFO listening addr=127.0.0.1:18080 pid=3315
# 2026/11/28 15:52:21 INFO shutting down grace=20s
# 2026/11/28 15:52:24 INFO stopped cleanly
# exit status 0
# slow: 200 after 3.002575s <- the in-flight request finished
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:18080/healthz; echo "curl exit $?"
# 000
# curl exit 7 <- connection refused: the listener is closed6. Slow headers (expected, not run)
# with ReadHeaderTimeout: 5s
(printf 'GET / HTTP/1.1\r\nHost: x\r\n'; sleep 10) | nc 127.0.0.1 8080
# expected: connection closed by the server after ~5 s, no response (a 408 is not sent for header timeouts)
# with http.ListenAndServe (no timeouts): nc stays connected for the full 10 sFor PHP/Laravel developers
In Laravel the web server and FPM own the connection: nginx enforces client_max_body_size and header timeouts, FPM's request_terminate_timeout is "The timeout for serving a single request after which the worker process will be killed", and each request starts from a clean process, so there is no shared client pool and no graceful-shutdown code in the app. In Go the binary is the server, so those limits move into http.Server and MaxBytesReader, and the shared, pooled http.Client is something you construct once. Routing maps closely: Laravel's docs say "Route parameters are always encased within {} braces", like Go 1.22 wildcards, and whereNumber('id') is the validation you do after r.PathValue("id"). $request->query('name') is r.URL.Query().Get("name"); $request->input('name'), which reads "the entire request payload (including the query string)", is closest to r.FormValue("name"). Laravel's HTTP client has defaults Go's lacks: "By default, the HTTP client will timeout after 30 seconds", and connectTimeout defaults to 10 s.
// routes/api.php — Laravel 13
Route::get('/users/{id}', [UserController::class, 'show'])->whereNumber('id'); // GET /users/{id} + ParseInt
Route::post('/users', [UserController::class, 'store']); // POST /users
$response = Http::timeout(3)->connectTimeout(1)->get('https://reviews.example.test/reviews', ['user' => $id]);
if ($response->failed()) { abort(502); } // StatusError -> 502| Laravel / PHP | Go net/http |
|---|---|
Route::get('/users/{id}', ...) | mux.HandleFunc("GET /users/{id}", ...) |
->whereNumber('id') | strconv.ParseInt(r.PathValue("id"), 10, 64) + 400 |
$request->query('page') | r.URL.Query().Get("page") |
$request->input('name') | r.FormValue("name") (or JSON decode) |
response()->json($u, 201) | jsonio.Write(w, http.StatusCreated, u) |
abort(404) | http.Error(w, ..., 404); return |
nginx client_max_body_size | http.MaxBytesReader |
FPM request_terminate_timeout | http.TimeoutHandler / ctx budget |
Http::timeout(3) | NewRequestWithContext with a 3 s child ctx |
php artisan serve / FPM restart | Shutdown with grace |
Common misconceptions
| Belief | Reality |
|---|---|
http.ListenAndServe is production-ready | All server timeouts are zero; build an http.Server |
/ is the home page | It matches every path; use GET /{$} |
| The first registered route wins | Most specific wins; order never matters; conflicts panic |
GET /x matches only GET | It also matches HEAD |
A catch-all / is harmless | It turns every 405 into 404 |
PathValue errors on a wrong name | It returns "" |
FormValue reads the query | Body first, then query, then multipart; errors ignored |
MaxHeaderBytes limits the body | Only line + headers; use MaxBytesReader |
http.Error returns from the handler | You must return |
WriteTimeout stops the handler | It closes the connection; the handler runs on |
TimeoutHandler answers 504 | It answers 503 (the 2016 Cloudflare article said 504) |
Shutdown cancels request contexts | It waits; it cancels nothing |
| A non-2xx response returns an error | err == nil; check StatusCode |
A new Transport per request is fine | The Transport is the pool; zero-value clients share DefaultTransport, custom Transports must be shared |
MaxIdleConnsPerHost defaults to something large | It is 2 |
| Closing the body is optional if you read it | Always close; before 1.27 also drain to reuse |
Client.Timeout excludes the body read | It includes it |
| ServeMux redirects with 301 | 307 since Go 1.26, for trailing slash and path cleaning |
Cheat sheet
| Topic | Remember |
|---|---|
| Mux | mux := http.NewServeMux(); never DefaultServeMux in services |
| Patterns | [METHOD ][HOST]/[PATH], {id}, {rest...}, {$}, trailing / = subtree |
| Precedence | Most specific wins; overlap with neither more specific panics |
| Path values | r.PathValue("id") → string, unescaped; parse + 400 |
| Route label | r.Pattern (1.23) for metrics |
| Query | q := r.URL.Query() once; q.Get, q["tag"] |
| Forms | ParseForm and check the error; FormValue ignores errors |
| Body | http.MaxBytesReader → *MaxBytesError → 413 |
| JSON in | DisallowUnknownFields, one value, 415/413/400/422 |
| Writing | Headers → WriteHeader → Write; return after http.Error |
| Server | ReadHeaderTimeout, ReadTimeout, WriteTimeout, IdleTimeout, MaxHeaderBytes |
| Shutdown | Shutdown(ctx); ErrServerClosed is normal; Close after grace |
| Streaming | NewResponseController(w): Flush, SetWriteDeadline |
| Client | One per upstream; MaxIdleConnsPerHost; Client.Timeout backstop |
| Requests | NewRequestWithContext(ctx, ...); defer resp.Body.Close() after err check |
| Tests | NewRecorder for handlers, NewServer for connections |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is http.ListenAndServe(":8080", mux) unsafe on the internet, and what do you write instead? Must-know
Answer
Answer: It creates an http.Server whose ReadHeaderTimeout, ReadTimeout, WriteTimeout and IdleTimeout are all zero, so a client that sends headers slowly holds a goroutine and a file descriptor forever (slowloris). Construct &http.Server{Addr: ..., Handler: mux, ReadHeaderTimeout: 5 * time.Second, ...} and call its ListenAndServe or Serve.
2 — You register GET /posts/{id} and GET /posts/latest. Which handles GET /posts/latest, and does registration order matter? Must-know
Answer
Answer: GET /posts/latest, because it matches a strict subset of the requests GET /posts/{id} matches. Order does not matter in Go 1.22+ ServeMux. If two patterns overlap and neither is more specific (/posts/{id} vs /{resource}/latest), the second registration panics.
3 — What does the pattern / match, and how do you serve a home page only at /? Must-know
Answer
Answer: / ends in a slash, so it is a subtree pattern that matches every path and every method. Use GET /{$}, which matches only the path /. A bare / catch-all also hides ServeMux's automatic 405 responses.
4 — A POST has ?name=q in the URL and name=b in a url-encoded body. What do r.FormValue("name") and r.URL.Query().Get("name") return? Important
Answer
Answer: FormValue returns b (url-encoded body first, then query, then multipart) and URL.Query().Get returns q. FormValue ignores parse errors, so call ParseForm yourself when you need to know about a malformed or oversized body.
5 — How do you stop a client from posting a 2 GB JSON body, and what status do you answer? Must-know
Answer
Answer: Wrap the body with r.Body = http.MaxBytesReader(w, r.Body, limit) before decoding; a read past the limit returns *http.MaxBytesError (http: request body too large) and the server closes the connection after the response. Answer 413 (StatusRequestEntityTooLarge). MaxHeaderBytes does not limit the body.
6 — A handler calls w.WriteHeader(201) and then w.Header().Set("Location", "/users/7"). What does the client get? Important
Answer
Answer: A 201 without Location: changes to the header map after WriteHeader (or the first Write) have no effect, except for 1xx statuses and trailers. Set every header first, then call WriteHeader.
7 — What happens to in-flight requests and to ListenAndServe when you call srv.Shutdown(ctx)? Must-know
Answer
Answer: ListenAndServe returns http.ErrServerClosed immediately; listeners and idle connections are closed; active requests keep running and Shutdown waits for them, without canceling their contexts, until they finish or ctx expires (then it returns ctx.Err() and you may call Close). The program must wait for Shutdown to return instead of exiting when ListenAndServe returns.
8 — Why does an SSE endpoint die after exactly WriteTimeout, and how do you fix it without removing the timeout for every route? Important
Answer
Answer: WriteTimeout is an absolute deadline set when the headers are read; it does not slide as bytes flow. Use rc := http.NewResponseController(w): clear the deadline with rc.SetWriteDeadline(time.Time{}) before waiting for the first event (an expired deadline cannot be extended, and HTTP/2 enforces that), set time.Now().Add(d) before each event write, rc.Flush() after it, clear it again while idle, and stop if SetWriteDeadline returns an error. Do not wrap the route in http.TimeoutHandler, which does not support Flusher.
9 — Your service builds &http.Client{Transport: &http.Transport{...}} inside every handler and never closes response bodies on error paths. What do you see under load? Must-know
Answer
Answer: No connection reuse, because each call has its own empty pool: a new TCP (and TLS) handshake per call, thousands of TIME_WAIT sockets, rising latency and eventually dial errors from ephemeral port exhaustion; unclosed bodies also leak the connection and its read/write goroutines. Share one client (and its Transport) per upstream, defer resp.Body.Close() right after the error check, and size MaxIdleConnsPerHost (default 2). A bare &http.Client{} per handler would still reuse connections through the shared DefaultTransport, but it has no timeout.
10 — http.Client.Timeout vs a context from NewRequestWithContext: what does each cover and why use both? Important
Answer
Answer: Both cover the whole exchange including the body read; Client.Timeout also spans redirects. Only the context knows the caller's remaining budget and the caller's disconnect. Use the context for the real per-call budget and Client.Timeout as a generous backstop for code paths that forget one.
11 — client.Do returned err == nil and resp.StatusCode == 500. Is that an error, and what must you still do? Important
Answer
Answer: For net/http it is a successful round trip; the 500 is data. Your code must check the status, read at most a bounded part of the body for the message, and still close the body. Map it to your own error (502 for an upstream failure).
12 — When is chi worth adding to a Go 1.22+ project, and why are gin and echo a bigger step? Good to know
Answer
Answer: chi pays off for route groups with their own middleware, sub-routers, regex segments and several wildcards in one segment, and it keeps http.Handler signatures. gin and echo use their own context types (*gin.Context, *echo.Context), so standard handlers and middleware need adapters; you get binding and rendering in exchange.
13 — What does http.CrossOriginProtection (Go 1.25) check, and what does it not protect? Good to know
Answer
Answer: It rejects non-safe (not GET, HEAD, OPTIONS) cross-origin browser requests with 403, using Sec-Fetch-Site or comparing Origin with Host; requests with neither header are allowed. It does not protect GET handlers that change state, and it is not CORS.
14 — Which httptest tool do you use to test a handler's status codes, and which to prove connection reuse? Important
Answer
Answer: httptest.NewRecorder with httptest.NewRequest for handlers and routing: in-memory and fast. For connections, timeouts, keep-alive and streaming you need a real server: httptest.NewUnstartedServer, with Config.ConnState counting StateNew, or httptrace.ClientTrace.GotConn checking Reused.
Glossary
| Term | Meaning |
|---|---|
net/http | Go standard-library package with the HTTP server, client, router and helpers |
http.Handler | Interface with ServeHTTP(ResponseWriter, *Request) |
http.HandlerFunc | Function type adapting a plain function to Handler |
http.ServeMux | The standard router: patterns to handlers, most specific wins |
DefaultServeMux | Global mux used by http.HandleFunc and a nil Server.Handler |
| Pattern | [METHOD ][HOST]/[PATH] string registered on a ServeMux |
| Wildcard | {name} (one segment) or {name...} (rest of path) in a pattern |
{$} | End anchor: the path must end here |
| Precedence rule | The pattern matching a strict subset of requests wins |
| Pattern conflict | Overlapping patterns where neither is more specific; panics at registration |
r.PathValue | Returns a wildcard's unescaped value, "" if absent |
Request.Pattern | The pattern that matched (Go 1.23) |
GODEBUG=httpmuxgo121 | Restores the pre-1.22 ServeMux matcher |
http.Request | Incoming or outgoing request: method, URL, headers, body, context |
URL.Query | Parses the raw query into url.Values |
url.Values | map[string][]string for query and form data |
ParseForm | Fills r.Form and r.PostForm; 10 MB cap without a limit |
r.FormValue | First value from body form, query, multipart; ignores errors |
http.MaxBytesReader | Body reader that fails past a limit with *MaxBytesError |
ResponseWriter | Interface to write headers, status and body |
WriteHeader | Sends the status line; at most one 2xx–5xx |
Header().Set | Sets a response header before the status is sent |
http.Error | Writes a plain-text error; does not return for you |
| Status code | Three-digit result class defined by RFC 9110 |
| Problem details | application/problem+json error body (RFC 9457) |
| NDJSON | One JSON value per line; streamable |
| Content negotiation | Choosing the response format from Accept |
http.FileServerFS | Handler serving an fs.FS (Go 1.22) |
http.ServeFileFS | Serves one file from an fs.FS (Go 1.22) |
embed | //go:embed compiles files into the binary |
http.StripPrefix | Removes a URL prefix before calling a handler |
| Redirect | 3xx response with Location; 303 after POST, 307/308 keep the method |
| Cookie | Set-Cookie state with HttpOnly, Secure, SameSite attributes |
http.Server | Listener loop, connection handling, timeouts, shutdown |
ListenAndServe | Listens on TCP and serves; returns only with an error |
ReadHeaderTimeout | Time allowed to read request headers |
ReadTimeout | Time allowed to read the whole request |
WriteTimeout | Deadline for writing the response, reset per request |
IdleTimeout | How long a keep-alive connection may wait for the next request |
| Slowloris | Attack that holds connections open by sending headers very slowly |
http.TimeoutHandler | Wrapper answering 503 after a time limit |
ErrHandlerTimeout | Error for writes after TimeoutHandler fired |
ErrAbortHandler | Panic value that aborts a response without logging |
| Graceful shutdown | Stop accepting, finish in-flight requests, then exit |
Shutdown | Server method performing graceful shutdown |
BaseContext | Server hook returning the root context of all requests |
ErrServerClosed | http: Server closed, returned by Serve after shutdown |
http.ResponseController | Per-request flush, deadlines, hijack (Go 1.20), full duplex (Go 1.21) |
SetWriteDeadline | ResponseController method overriding the write deadline |
Flusher | Optional interface to push buffered bytes |
| SSE | Server-Sent Events: text/event-stream, events separated by blank lines |
Hijacker | Optional interface to take over an HTTP/1 connection |
http.Client | High-level client: timeout, redirects, cookie jar |
Transport | RoundTripper that dials, pools connections and speaks HTTP/1 and HTTP/2 |
| Connection pooling | Reusing idle keep-alive connections across requests |
| Keep-alive | Persistent HTTP connection reused for several requests |
MaxIdleConnsPerHost | Idle connections kept per host (default 2) |
NewRequestWithContext | Builds an outgoing request bound to a context |
| Drain | Reading the rest of a body so its connection can be reused |
http.DefaultClient | Global client with no timeout, used by http.Get |
| HTTP/2 default | Go negotiates h2 over TLS automatically since Go 1.6 |
httptest | Recorder, test request and loopback test servers |
httptrace | Client hooks for connection, DNS and write events |
http.CrossOriginProtection | Fetch-metadata CSRF protection (Go 1.25) |
| chi / gin / echo | Third-party router (chi) and frameworks (gin, echo) |
References
- Jonathan Amsterdam, "Routing Enhancements for Go 1.22", The Go Blog, 13 February 2024: https://go.dev/blog/routing-enhancements
- "Go 1.22 is released!", The Go Blog: https://go.dev/blog/go1.22
net/httpserver source and doc comments (Go 1.27): https://go.dev/src/net/http/server.gonet/httpclient: https://go.dev/src/net/http/client.gonet/httptransport: https://go.dev/src/net/http/transport.gonet/httprequest (ParseForm,FormValue,PathValue,MaxBytesReader): https://go.dev/src/net/http/request.gonet/httpresponse (Bodycontract): https://go.dev/src/net/http/response.gonet/httppattern parser: https://go.dev/src/net/http/pattern.gonet/httprouting tree: https://go.dev/src/net/http/routing_tree.gonet/httpfile server: https://go.dev/src/net/http/fs.gonet/httpResponseController: https://go.dev/src/net/http/responsecontroller.gonet/httpCrossOriginProtection: https://go.dev/src/net/http/csrf.gonet/httpcookies: https://go.dev/src/net/http/cookie.gonet/httpstatus codes: https://go.dev/src/net/http/status.gonet/http/httptestserver: https://go.dev/src/net/http/httptest/server.gonet/http/httptestrecorder: https://go.dev/src/net/http/httptest/recorder.gonet/http/httptrace: https://go.dev/src/net/http/httptrace/trace.goencoding/jsonstream (Decoder,Encoder): https://go.dev/src/encoding/json/stream.goembedpackage: https://go.dev/src/embed/embed.go- Go 1.6 release notes (HTTP/2): https://go.dev/doc/go1.6
- Go 1.7 release notes (httptrace, IdleConnTimeout): https://go.dev/doc/go1.7
- Go 1.8 release notes (Shutdown, ReadHeaderTimeout, IdleTimeout): https://go.dev/doc/go1.8
- Go 1.16 release notes (embed, http.FS): https://go.dev/doc/go1.16
- Go 1.19 release notes (MaxBytesError): https://go.dev/doc/go1.19
- Go 1.20 release notes (ResponseController): https://go.dev/doc/go1.20
- Go 1.22 release notes (routing, ServeFileFS, PathValue): https://go.dev/doc/go1.22
- Go 1.23 release notes (Request.Pattern, cookies): https://go.dev/doc/go1.23
- Go 1.24 release notes (Protocols, unencrypted HTTP/2): https://go.dev/doc/go1.24
- Go 1.25 release notes (CrossOriginProtection): https://go.dev/doc/go1.25
- Go 1.26 release notes (307 slash redirects, NewClientConn): https://go.dev/doc/go1.26
- Go 1.27 release notes (Body drain on close, MaxHeaderValueCount, NewTestServer): https://go.dev/doc/go1.27
- Filippo Valsorda, "The complete guide to Go net/http timeouts", Cloudflare Blog, 29 June 2016: https://blog.cloudflare.com/the-complete-guide-to-golang-net-http-timeouts/
- Alex Edwards, "Which Go router should I use?" (updated May 2025): https://www.alexedwards.net/blog/which-go-router-should-i-use
- RFC 9110, HTTP Semantics: https://www.rfc-editor.org/rfc/rfc9110
- RFC 9112, HTTP/1.1: https://www.rfc-editor.org/rfc/rfc9112
- RFC 9113, HTTP/2: https://www.rfc-editor.org/rfc/rfc9113
- RFC 6265, HTTP State Management (cookies): https://www.rfc-editor.org/rfc/rfc6265
- WHATWG HTML, Server-sent events: https://html.spec.whatwg.org/multipage/server-sent-events.html
- MDN, Using server-sent events: https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
- MDN, Sec-Fetch-Site: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Sec-Fetch-Site
- chi README: https://github.com/go-chi/chi
- gin README: https://github.com/gin-gonic/gin
- echo README: https://github.com/labstack/echo
- Laravel 13, Routing: https://laravel.com/docs/13.x/routing
- Laravel 13, HTTP Requests: https://laravel.com/docs/13.x/requests
- Laravel 13, HTTP Client: https://laravel.com/docs/13.x/http-client
- PHP manual, FPM configuration: https://www.php.net/manual/en/install.fpm.configuration.php
ospackage source (DirFSsymlink note,Root.FS): https://go.dev/src/os/file.gonet/httpclient redirect behaviour (redirectBehavior) andDocontract: https://go.dev/src/net/http/client.go- RFC 9457, Problem Details for HTTP APIs: https://www.rfc-editor.org/rfc/rfc9457
- nginx
client_max_body_size(default1m): https://nginx.org/en/docs/http/ngx_http_core_module.html - Kubernetes, Pod lifecycle (termination grace period): https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/
- gin
Engineoptions (HandleMethodNotAllowed): https://raw.githubusercontent.com/gin-gonic/gin/master/gin.go - echo router (
MethodNotAllowedHandler): https://raw.githubusercontent.com/labstack/echo/master/router.go