HTTP
net/http runs in production as it is, but its zero values have no limits. This sheet shows the failures on real connections, and the settings that stop them.
- 1Every timeout on http.Server and http.DefaultClient is zero, and zero means no limit. Set them.
- 2One Transport per process. It holds the pool, and a new one per request dials every time.
- 3Close every response body. Read it to EOF to keep the connection.
- 4Stop a server with Shutdown: it stops accepting and waits for requests in flight.
package main
import (
"fmt"
"net"
"net/http"
"sync/atomic"
"time"
)
func main() {
var open atomic.Int64
srv := &http.Server{1
Handler: http.NotFoundHandler(),
ConnState: func2(_ net.Conn, s http.ConnState) {
switch s {
case http.StateNew:
open.Add(1)
case http.StateClosed:
open.Add(-1)
}
},
}
ln, _ := net.Listen("tcp", "127.0.0.1:0")
go srv.Serve(ln)
for range 100 {
c, _ := net.Dial("tcp", ln.Addr().String())
defer c.Close()
c.Write([]byte("GET / HTTP/1.1\r\nHost: x\r\n"3))
}
time.Sleep(time.Second)4
fmt.Println("open connections after 1 s:", open.Load())
}- 1No timeout fields. http.ListenAndServe builds the same server.
- 2Counts connections that the server holds open.
- 3The headers never end: no blank line follows. The server waits for the rest.
- 4The clients send nothing more.
| server | recorded output | status |
|---|---|---|
| http.Server{} | open connections after 1 s: 100 | Held forever |
| ReadHeaderTimeout: 200 ms | open connections after 1 s: 0 | All closed |
- This attack is a slow-loris: many connections, each one sends a request very slowly.
- Each held connection costs a goroutine and about 9 KB here.
- The real limit is file descriptors. At the limit, accept fails and normal clients wait (panel Q).
- A load balancer in front helps, but it holds the same connections unless it also has a limit.
A server with no timeouts holds a connection for as long as a client wants. I set ReadHeaderTimeout on every server.
- WriteTimeout starts when the headers end, so it also limits the handler.
- The TLS handshake uses the smallest of the three positive read and write limits.
- http.NewResponseController can change a deadline for one request, for example a long download.
ReadHeaderTimeout covers the headers, ReadTimeout adds the body, WriteTimeout covers the response, and IdleTimeout covers keep-alive.
| server sets | slow headers | slow body | idle keep-alive | slow reader |
|---|---|---|---|---|
| all zero | 10 | 10 | 10 | 10 |
| ReadHeaderTimeout | 0 | 10 | 10 | 10 |
| and ReadTimeout | 0 | 0 | 0 | 10 |
| and WriteTimeout | 0 | 0 | 0 | 0 |
- Each row adds one field to the row above it.
- The two slow attacks send a few bytes every 40 ms. The deadline is absolute, so this does not extend it.
- ReadTimeout also stops the idle attack, because IdleTimeout falls back to it. Set IdleTimeout too.
- ReadTimeout limits uploads. For a large upload, use ReadHeaderTimeout and a deadline in the handler.
Each attack needs its own field. ReadHeaderTimeout alone leaves slow bodies, idle connections and slow readers open.
| pattern | matches |
|---|---|
| GET /items/{id} | One segment. Read it with r.PathValue("id"). GET also matches HEAD. |
| /files/{path...} | The rest of the path, slashes included. |
| /static/ | A subtree: everything under it. |
| /{$} | Only the root path. |
| example.com/ | That host. A host pattern wins over a pattern with no host. |
| rule | result |
|---|---|
| /items/new against /items/{id} | The literal wins. |
| GET /x against /x | The method wins. |
| Two patterns overlap, neither is more specific | Panic at registration. |
| Path matches, method does not | 405 with an Allow header. |
| /x when only /x/ exists | 307 to /x/, since Go 1.26. |
GET /items/{id} and /items/new conflict: one has the method, the other has the literal. Our first draft of the drill panicked on this pair.
// Routes builds the handler for the service.
func Routes(s *Store, log *slog.Logger) http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /items/{id}", s.get)
mux.HandleFunc("GET /items/new"1, s.form)
mux.HandleFunc("POST /items", s.create)
mux.HandleFunc("GET /report", s.slow)
mux.HandleFunc("GET /files/{path...}2", s.file)
mux.HandleFunc("GET /{$}3", s.home)
return Chain(mux, Recover(log), Logging(log))4
}
func (s *Store) get(w http.ResponseWriter, r *http.Request) {
s.mu.Lock()
item, ok := s.items[r.PathValue("id")5]
s.mu.Unlock()
if !ok {
http.Error(w, "no such item", http.StatusNotFound)
return
}
writeJSON(w, http.StatusOK, item)
}- 1More specific than GET /items/{id}, so registration order does not matter.
- 2A wildcard for the rest of the path. It must be the last segment.
- 3Without it, "GET /" would be a subtree and would match every GET.
- 4Middleware wraps the whole mux. See panel E.
- 5The value of the wildcard, since Go 1.22.
The most specific pattern wins, and a conflict panics at startup, so the routing table cannot be ambiguous at run time.
// Middleware wraps one handler in another.
type Middleware func(http.Handler) http.Handler
// Chain applies mw so that the first one runs first.
func Chain(h http.Handler, mw ...Middleware) http.Handler {
for _, m := range slices.Backward(mw)1 {
h = m(h)
}
return h
}
// statusWriter records what the handler sent.
type statusWriter struct {
http.ResponseWriter
status int
}
func (w *statusWriter) WriteHeader(code int) {
w.status = code
w.ResponseWriter.WriteHeader(code)
}
// Unwrap lets http.ResponseController reach the real writer.
func (w *statusWriter) Unwrap()3 http.ResponseWriter {
return w.ResponseWriter
}
// Logging writes one line per request.
func Logging(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(
w http.ResponseWriter, r *http.Request,
) {
start := time.Now()
sw := &statusWriter{ResponseWriter: w, status: 2002}
next.ServeHTTP(sw, r)
log.InfoContext(r.Context(), "request",
"pattern", r.Pattern4, "status", sw.status,
"ms", time.Since(start).Milliseconds())
})
}
}
// Recover turns a panic into a 500 and a log line.
func Recover(log *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(
w http.ResponseWriter, r *http.Request,
) {
defer func() {
v := recover()
if v == nil {
return
}
if v == http.ErrAbortHandler5 {
panic(v)
}
log.ErrorContext(r.Context(), "panic", "value", v)
http.Error(w, "internal error", 500)6
}()
next.ServeHTTP(w, r)
})
}
}- 1Wrap from the last to the first, so the first in the list is the outermost.
- 2A handler that never calls WriteHeader sends 200.
- 3A wrapper hides Flusher and deadlines. Unwrap lets ResponseController find them.
- 4The matched pattern, since Go 1.23. Use it as a metric label: it has a fixed set of values.
- 5A handler uses this panic to abort on purpose, so pass it on.
- 6This has no effect on the status if the handler already wrote.
Middleware is a function from handler to handler. The first in the list runs first, and I wrap ResponseWriter only with an Unwrap method.
// NewServer sets every limit. The zero value of each one means
// no limit at all.
func NewServer(
addr string, h http.Handler, log *slog.Logger,
) *http.Server {
return &http.Server{
Addr: addr,
Handler: h,
ReadHeaderTimeout: 5 * time.Second1,
ReadTimeout: 30 * time.Second2,
WriteTimeout: 30 * time.Second3,
IdleTimeout: 2 * time.Minute4,
MaxHeaderBytes: 64 << 105,
ErrorLog: slog.NewLogLogger(6
log.Handler(), slog.LevelWarn),
}
}- 1Closes the slow-loris from panel A.
- 2Headers and body together. Above the largest upload you accept.
- 3Above the slowest handler. Past it, the client gets a closed connection, not a status.
- 4Keep-alive connections end here. Keep it above the load balancer idle timeout.
- 5The default is 1 MB.
- 6net/http writes accept errors and panics to ErrorLog, so send them to the structured log.
| rule | status |
|---|---|
| Pass ctx with its own budget in each handler | Approved |
| http.ListenAndServe in production | No timeouts |
| http.TimeoutHandler on a streaming route | It buffers the response |
My constructor sets every limit, and a test fails if one is zero.
// Run serves until ctx ends, then drains requests for up to
// grace, then closes what remains.
func Run(
ctx context.Context, srv *http.Server, ln net.Listener,
grace time.Duration,
) error {
errc := make(chan error, 1)1
go func() { errc <- srv.Serve(ln) }()
select {
case err := <-errc:
return fmt.Errorf("serve: %w", err)
case <-ctx.Done():
}
drain, cancel := context.WithTimeout(
context.WithoutCancel(ctx)2, grace)
defer cancel()
if err := srv.Shutdown(drain)3; err != nil {
return errors.Join(
fmt.Errorf("shutdown: %w", err), srv.Close()4)
}
if err := <-errc; !errors.Is(err, http.ErrServerClosed5) {
return fmt.Errorf("serve: %w", err)
}
return nil
}- 1One slot, so the Serve goroutine can always exit.
- 2ctx has already ended. The drain needs a new deadline from its values.
- 3Closes listeners, closes idle connections, and waits for active ones.
- 4The deadline passed. Close the connections that remain.
- 5Serve returns this after Shutdown. It is the normal case.
| recorded output, in order |
|---|
| signal: terminated signal received |
| shutdown: <nil> |
| in-flight request: 200 OK |
| serve closed: true |
| new request refused: true |
- Create ctx in main with signal.NotifyContext. Since Go 1.26, context.Cause names the signal.
- Shutdown does not cancel request contexts. To stop long handlers, connect BaseContext to your own signal.
- Shutdown ignores hijacked connections. Close WebSockets with RegisterOnShutdown.
- Keep the grace below the platform kill timeout. Kubernetes defaults to 30 s.
On SIGTERM I fail readiness, call Shutdown with a deadline, and let requests in flight finish. After the deadline I call Close.
// ReadJSON reads one JSON value of at most MaxBody bytes.
func ReadJSON(w http.ResponseWriter, r *http.Request, v any) error {
r.Body = http.MaxBytesReader(w, r.Body, MaxBody)1
dec := json.NewDecoder(r.Body)
dec.DisallowUnknownFields()3
if err := dec.Decode(v); err != nil {
_, big := errors.AsType[*http.MaxBytesError](err)2
if big {
return ErrTooLarge
}
return fmt.Errorf("%w: %v", ErrInvalid, err)
}
if err := dec.Decode(&struct{}{})4; !errors.Is(err, io.EOF) {
return fmt.Errorf("%w: data after the value", ErrInvalid)
}
return nil
}- 1Returns an error past the limit, and marks the connection to close after the response.
- 2The typed error survives the decoder. Answer 413.
- 3See G15 for why, and for the v2 form.
- 4Rejects data after the first value.
The server closes r.Body itself. A handler needs no Close, and unread request data up to 256 KB is read for you.
MaxBytesReader limits the body and tells the server to close the connection. io.ReadAll with no limit lets a client choose my memory use.
// slow answers GET /report. The context ends when the client
// leaves or when the budget ends.
func (s *Store) slow(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(2
r.Context()1, 2*time.Second)
defer cancel()
out, err := s.report(ctx)
switch {
case errors.Is(err, context.Canceled)3:
return // The client left, so no one reads a response.
case errors.Is(err, context.DeadlineExceeded):
http.Error(w, "backend too slow", http.StatusGatewayTimeout4)
case err != nil:
http.Error(w, "backend failed", http.StatusBadGateway)
default:
writeJSON(w, http.StatusOK, map[string]string{"report": out})
}
}- 1Ends when the client disconnects, when the HTTP/2 stream resets, or when ServeHTTP returns.
- 2A budget for this call, below WriteTimeout, so the client gets a real status.
- 3The client left. Do not count this as a server error.
- 4The budget ended first: answer 504.
| rule | status |
|---|---|
| Work after the response: context.WithoutCancel | With its own timeout |
| Use r.Context in a goroutine that outlives the handler | It ends at return |
| Use r, w after the handler returns | Not approved |
r.Context ends when the client leaves. I add a budget and pass it to every call, so the work stops when the answer has no reader.
// ServeTLS serves HTTPS, with HTTP/2 on by default.
func ServeTLS(
srv *http.Server, ln net.Listener, cert tls.Certificate,
) error {
srv.TLSConfig = &tls.Config{
MinVersion: tls.VersionTLS121,
Certificates: []tls.Certificate{cert},
}
return srv.ServeTLS(ln, "", "")2
}- 1A test proves that a TLS 1.1 client fails here.
- 2Empty file names: the certificate comes from TLSConfig.
| rule | status |
|---|---|
| Use GetCertificate to rotate a certificate with no restart | Approved |
| Set timeouts: they also limit the handshake | Approved |
| InsecureSkipVerify in production | Not approved |
| Set a CipherSuites list for TLS 1.3 | It has no effect on 1.3 |
A new HTTPS connection costs 2.22 ms here, and a reused one costs 0.07 ms. Reuse matters most with TLS.
net/http negotiates HTTP/2 over TLS with no extra code. I set a minimum version, and I terminate at the load balancer if the platform does.
- A client and a Transport are safe for concurrent use, so share them.
- Each connection costs 2 goroutines in the client: readLoop and writeLoop.
- Each host keeps 2 idle connections by default, a low limit for a busy service.
Client is a small wrapper. Transport owns the pool. A connection returns to the pool when its body reaches EOF.
| rule | why | status |
|---|---|---|
| One Transport per process | It holds the pool. | Approved |
| Clone DefaultTransport, then change it | Keeps the proxy, dial and TLS limits. | Approved |
| Set Client.Timeout or a ctx deadline | The default is none. | Approved |
| Raise MaxIdleConnsPerHost for one busy host | The default of 2 forces new connections. | Approved |
| defer resp.Body.Close() after the err check | On error, resp is nil. | Approved |
| http.Get in production | It uses DefaultClient, with no timeout. | Not approved |
| A new Client or Transport per request | Each one dials, and keeps its idle connection. | Not approved |
| Treat err == nil as success | A 500 returns nil. | Not approved |
Client.Timeout includes reading the body, so a streaming download needs a ctx instead.
The default client has no timeout, so one stuck server can stop a goroutine forever. Each call has a context or a client timeout.
// NewClient returns the one client a process shares. Its
// Transport keeps the connection pool, so create it once.
func NewClient() *http.Client {
t := http.DefaultTransport.(*http.Transport).Clone()1
t.MaxIdleConns = 100
t.MaxIdleConnsPerHost = 32
t.ResponseHeaderTimeout2 = 5 * time.Second
return &http.Client{Transport: t, Timeout: 10 * time.Second3}
}- 1Keeps the proxy, HTTP/2 and dial settings.
- 2Limits the wait for the first response byte.
- 3Limits the whole call, including the body.
// GetJSON fetches url into v. On every path it ends with the
// body read and closed, so the connection returns to the pool.
func GetJSON(
ctx context.Context, c *http.Client, url string, v any,
) error {
req, err := http.NewRequestWithContext(1
ctx, http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("new request: %w", err)
}
resp, err := c.Do(req)
if err != nil {
return fmt.Errorf("get: %w", err)
}
defer discard(resp)2
if resp.StatusCode != http.StatusOK3 {
return &StatusError{resp.StatusCode}
}
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return fmt.Errorf("decode: %w", err)
}
return nil
}
// discard reads what is left, up to a limit, and closes. A
// failed read costs only this connection, so it needs no report.
func discard(resp *http.Response) {
_, _ = io.CopyN(io.Discard, resp.Body, maxDrain)4
resp.Body.Close()
}- 1The context can cancel the request at any stage.
- 2After the err check, because resp is nil on error.
- 3A 500 arrives here with err == nil.
- 4A bound: an endless body cannot hold this call.
I build one client at startup. After each call I read what is left, up to a limit, and close the body, so the connection goes back to the pool.
| client code | requests | opened | open at end | goroutines | |
|---|---|---|---|---|---|
| read to EOF, then Close | 200 | 1 | 1 | 3 | Approved |
| Close only, 1 KB body | 200 | 1 | 1 | 3 | Approved |
| Close only, 1 MB body | 200 | 200 | 0 | 0 | Not approved |
| Close only, body still arriving | 50 | 50 | 0 | 0 | Not approved |
| decode one value, then Close | 200 | 1 | 1 | 3 | Approved |
| read to EOF, no Close | 200 | 1 | 1 | 3 | Reuses, but still call Close |
| no read, no Close | 200 | 200 | 200 | 600 | Not approved |
| new Transport per request | 200 | 200 | 200 | 600 | Not approved |
| 32 workers, idle limit 2 | 1000 | 374 | 2 | 6 | Not approved |
| 32 workers, idle limit 32 | 1000 | 33 | 32 | 96 | Approved |
Goroutines are the growth in the process: 2 in the client and 1 in the server per open connection.
- Each opened connection costs about 0.13 ms more on loopback, and more across a network.
- On Go 1.26 the 1 KB row opens 200 connections: we ran it. Go 1.27 opens 1.
- The drain runs after Close returns, so a request that follows at once can dial a second connection.
- A leak shows up as a growing connection count and goroutine count, not as an error.
Below 256 KB, Go 1.27 drains on Close for up to 50 ms. Above that, Close drops the connection. With no Close, the connection leaks.
// Retry sends req up to tries times, with exponential backoff
// and jitter. Only an idempotent request is sent twice.
func Retry(
ctx context.Context, c *http.Client, req *http.Request,
tries int,
) (*http.Response, error) {
if !idempotent(req)1 {
tries = 1
}
delay := 100 * time.Millisecond
for try := 1; ; try++ {
resp, err := send(ctx, c, req)
if try == tries || !transient(ctx, resp, err) {
return resp, err
}
wait := delay/2 + rand.N(delay/2)2
if resp != nil {
wait = max(wait, retryAfter(resp))3
discard(resp)4
}
select {
case <-time.After(wait):
case <-ctx.Done():5
return nil, context.Cause(ctx)
}
delay *= 2
}
}
// send makes a fresh copy of req, with a rewound body.
func send(
ctx context.Context, c *http.Client, req *http.Request,
) (*http.Response, error) {
r := req.Clone(ctx)6
if req.GetBody != nil {
body, err := req.GetBody()7
if err != nil {
return nil, fmt.Errorf("rewind body: %w", err)
}
r.Body = body
}
return c.Do(r)
}
func idempotent(r *http.Request) bool {
switch r.Method {
case http.MethodGet, http.MethodHead, http.MethodPut,
http.MethodDelete:
return true
}
return r.Header.Get("Idempotency-Key") != ""
}
func transient(
ctx context.Context, resp *http.Response, err error,
) bool {
if ctx.Err() != nil {
return false
}
if err != nil {
return true
}
switch resp.StatusCode {
case 429, 502, 503, 504:8
return true
}
return false
}
func retryAfter(resp *http.Response) time.Duration {
s, err := strconv.Atoi(resp.Header.Get("Retry-After"))
if err != nil || s < 0 {
return 0
}
return time.Duration(s) * time.Second
}- 1A retry of a POST can charge twice. An Idempotency-Key makes it safe; see the design sheets.
- 2Jitter spreads clients that failed together.
- 3The server knows its own recovery time.
- 4Read and close before the next try, or each retry costs a connection.
- 5The total budget lives in ctx, not in the number of tries.
- 6A request is single use. Each try needs a fresh copy.
- 7A body is a stream. NewRequest sets GetBody for common readers, so it can rewind.
- 8Only statuses that can change. A 400 will fail again.
I retry only idempotent requests, with backoff and jitter, and I stop at the context deadline. A POST needs an idempotency key first.
func TestRoutes(t *testing.T) {
h := newRoutes()
tests := []struct {
method, path, body string
want int
}{
{"POST", "/items", `{"name":"pen"}`, 201},
{"GET", "/items/1", "", 200},
{"GET", "/items/2", "", 404},
{"GET", "/items/new", "", 200},
{"DELETE", "/items", "", 405},
{"POST", "/items", `{"nam":"pen"}`, 400},
{"POST", "/items", `{"name":"a"} x`, 400},
}
for _, tt := range tests {
t.Run(tt.method+" "+tt.path, func(t *testing.T) {
w := httptest.NewRecorder()1
r := httptest.NewRequest(2
tt.method, tt.path, strings.NewReader(tt.body))
h.ServeHTTP(w, r)3
if w.Code != tt.want {
t.Fatalf("got %d: %s", w.Code, w.Body)
}
})
}
}- 1A ResponseWriter that records. No socket, so thousands of cases run in a second.
- 2A server-side request. Use http.NewRequest only for a client.
- 3Through the mux and the middleware, as in production.
func TestReportHasABudget(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
store := NewStore(
func(ctx context.Context) (string, error) {
<-ctx.Done()
return "", ctx.Err()
})
srv := httptest.NewTestServer(1
t, Routes(store, discardLog()))
start := time.Now()
resp, err := srv.Client().Get("http://x/report")2
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("got %d", resp.StatusCode)
}
if d := time.Since(start); d != 2*time.Second3 {
t.Fatalf("took %v", d)
}
})
}- 1Go 1.27: an in-memory network, so synctest can see every goroutine.
- 2The client sends every host to this server.
- 3An exact check: the test takes no real time.
| tool | use it for |
|---|---|
| NewRecorder | Handler logic and routes |
| NewTestServer | Client code, timeouts, retries |
| server.Start | Real TCP: connection counts, keep-alive |
NewRecorder tests a handler with no network. NewTestServer gives a whole client and server in memory, on the fake clock of synctest.
t = 986 ms
94 attack connections are open.
A normal request timed out after 80 ms.
25 of 30 normal requests failed; 10 accept errors logged.
- Attack connections open
- Normal request failed
- Normal request served
- Dashed line: the limit of 64 file descriptors
- The server runs in its own process with a limit of 64 file descriptors. Your real limit is higher, and the shape is the same.
- The attacker opens 10 connections every 100 ms, up to 200, and sends one header line every 200 ms.
- With no timeout, normal requests fail from 512 ms: 25 of 30 fail, and the server logs "accept tcp 127.0.0.1:64306: accept: too many open files".
- With a timeout of 300 ms, the open count peaks at 40, and every normal request succeeds.
- Click a column to read that moment. Each failed request waited for a server that could not accept.
The attack does not need bandwidth. It needs the file descriptor limit, so a short header timeout keeps the open count below it.
| since | what changed | what it means here |
|---|---|---|
| 1.20 | http.ResponseController with SetReadDeadline and SetWriteDeadline. ReverseProxy.Rewrite. | Per-request deadlines with no type assertions. |
| 1.21 | ResponseController.EnableFullDuplex. ErrSchemeMismatch. | An HTTP/1 handler can read and write together. |
| 1.22 | ServeMux accepts methods and wildcards. Request.PathValue and SetPathValue. | Most routers are no longer needed. |
| 1.23 | Request.Pattern. Spaces or tabs after the method. ParseCookie, ParseSetCookie. | Log the pattern, not the path. |
| 1.24 | Server.Protocols, Transport.Protocols and the HTTP2 config field. Unencrypted HTTP/2. | h2c needs no extra module. |
| 1.25 | http.CrossOriginProtection. testing/synctest. | CSRF protection with no tokens. |
| 1.26 | ServeMux trailing-slash redirects use 307. Transport.NewClientConn. HTTP2Config.StrictMaxConcurrentRequests. signal.NotifyContext sets a cause. | A POST to /x keeps its method through the redirect. |
| 1.27 | HTTP/1 Response.Body drains on Close, up to a limit. Server.MaxHeaderValueCount. httptest.NewTestServer. The HTTP/2 server accepts RFC 9218 priorities, and Server.DisableClientPriority turns that off. | Small unread bodies keep their connection. Timeouts can be tested on a fake clock. |
| when | the moment | what to do or say |
|---|---|---|
| build | You type main.go from the K1 kit. | http.ListenAndServe is fine for 45 minutes. It has no timeouts, so name that in the talk. |
| build | The kit registers GET /items/{key}. | Use the method and the wildcard. ServeMux gives you 405 and path values for free. |
| build | You add a route with a literal segment. | Run the program once: a conflict panics at startup, and the message names both patterns. |
| build | The handler needs a test. | A table with NewRecorder, as in the kit's do helper. Go through routes, not through the handler alone. |
| talk | "What do you change for production?" | NewServer with timeouts, Shutdown on SIGTERM, MaxBytesReader, and a Recover and a Logging middleware. |
| talk | "What does a zero timeout mean?" | No limit. Then name which field stops which attack: panel C has the recorded table. |
| talk | "The service calls another service. What do you set?" | One shared client, a Timeout, a ctx with the request budget, MaxIdleConnsPerHost, and retries for idempotent calls only. |
| talk | "Connections to a dependency keep growing." | Look for a body with no Close, a Transport per request, or an idle limit of 2 under load. Panel N has the counts. |
The kit server has no timeouts on purpose. In the talk I say so first, and I list what I would add.
0 of 11 known
Predict the output. Each line shows the pattern that matched.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() for _, p := range []string{ "/items/{id}", "GET /items/new", "GET /items/{id}", "/", } { mux.HandleFunc(p, func(w http.ResponseWriter, r *http.Request) { fmt.Println(r.Method, r.URL.Path, "->", r.Pattern) }) } for _, t := range [][2]string{ {"GET", "/items/new"}, {"POST", "/items/new"}, {"GET", "/items/7"}, {"PUT", "/items/7"}, {"GET", "/items/7/parts"}, } { w := httptest.NewRecorder() mux.ServeHTTP(w, httptest.NewRequest(t[0], t[1], nil)) } }Predict the output: status, then the Allow header.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("GET /items", func(http.ResponseWriter, *http.Request) {}) for _, method := range []string{"GET", "HEAD", "POST"} { w := httptest.NewRecorder() mux.ServeHTTP(w, httptest.NewRequest(method, "/items", nil)) fmt.Println(method, w.Code, w.Header().Get("Allow")) } }Predict the output: path, status, Location.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/static/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "subtree") }) mux.HandleFunc("/exact/{$}", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "exact") }) for _, path := range []string{"/static/a/b", "/static", "/exact/", "/exact/x"} { w := httptest.NewRecorder() mux.ServeHTTP(w, httptest.NewRequest("GET", path, nil)) fmt.Println(path, w.Code, w.Header().Get("Location")) } }Does this program print "registered both"? The deferred function prints whether the panic mentions a conflict.
package main import ( "fmt" "net/http" "strings" ) func main() { defer func() { text := fmt.Sprint(recover()) first, _, _ := strings.Cut(text, "\n") fmt.Println(strings.Contains(first, "conflicts")) }() mux := http.NewServeMux() mux.HandleFunc("/{a}/x", func(http.ResponseWriter, *http.Request) {}) mux.HandleFunc("/y/{b}", func(http.ResponseWriter, *http.Request) {}) fmt.Println("registered both") }Predict the output.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { h := func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "body") w.Header().Set("X-Late", "1") } srv := httptest.NewServer(http.HandlerFunc(h)) defer srv.Close() resp, err := http.Get(srv.URL) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println(resp.StatusCode, "X-Late:", resp.Header.Get("X-Late")) }Predict the output. The server answers 500.
package main import ( "fmt" "net/http" "net/http/httptest" ) func main() { srv := httptest.NewServer(http.HandlerFunc( func(w http.ResponseWriter, r *http.Request) { http.Error(w, "boom", 500) })) defer srv.Close() resp, err := http.Get(srv.URL) fmt.Println(err) defer resp.Body.Close() fmt.Println(resp.StatusCode) }Predict the output. The client posts "hi" to each path.
package main import ( "fmt" "io" "net/http" "net/http/httptest" "strings" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/end", http.StatusFound) }) mux.HandleFunc("/b", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/end", http.StatusTemporaryRedirect) }) mux.HandleFunc("/end", func(w http.ResponseWriter, r *http.Request) { b, _ := io.ReadAll(r.Body) fmt.Fprintf(w, "%s body=%q", r.Method, b) }) srv := httptest.NewServer(mux) defer srv.Close() for _, path := range []string{"/a", "/b"} { resp, _ := http.Post(srv.URL+path, "text/plain", strings.NewReader("hi")) b, _ := io.ReadAll(resp.Body) resp.Body.Close() fmt.Println(path, string(b)) } }Predict the output.
package main import ( "fmt" "io" "net/http/httptest" "strings" ) func main() { r := httptest.NewRequest("POST", "/", strings.NewReader("hello")) first, _ := io.ReadAll(r.Body) second, _ := io.ReadAll(r.Body) fmt.Printf("%q %q\n", first, second) }Predict the output. The limit is 4 bytes and the body has 10.
package main import ( "errors" "fmt" "io" "net/http" "net/http/httptest" "strings" ) func main() { h := func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 4) b, err := io.ReadAll(r.Body) var tooBig *http.MaxBytesError fmt.Printf("%q %v\n", b, errors.As(err, &tooBig)) http.Error(w, "too large", http.StatusRequestEntityTooLarge) } srv := httptest.NewServer(http.HandlerFunc(h)) defer srv.Close() resp, err := http.Post(srv.URL, "text/plain", strings.NewReader("0123456789")) if err != nil { panic(err) } defer resp.Body.Close() fmt.Println(resp.StatusCode, "close:", resp.Close) }Predict the output.
package main import ( "errors" "fmt" "io" "log" "net/http" "net/http/httptest" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/boom", func(http.ResponseWriter, *http.Request) { panic("boom") }) mux.HandleFunc("/ok", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "alive") }) srv := httptest.NewUnstartedServer(mux) srv.Config.ErrorLog = log.New(io.Discard, "", 0) srv.Start() defer srv.Close() _, err := http.Get(srv.URL + "/boom") fmt.Println(errors.Is(err, io.EOF)) resp, err := http.Get(srv.URL + "/ok") if err != nil { panic(err) } defer resp.Body.Close() b, _ := io.ReadAll(resp.Body) fmt.Println(string(b)) }Predict the output: server timeouts, client timeouts, idle limits, then Transport timers.
package main import ( "fmt" "net/http" ) func main() { var s http.Server fmt.Println(s.ReadHeaderTimeout, s.ReadTimeout, s.WriteTimeout, s.IdleTimeout) t := http.DefaultTransport.(*http.Transport) fmt.Println(http.DefaultClient.Timeout, t.ResponseHeaderTimeout) fmt.Println(t.MaxIdleConns, t.MaxIdleConnsPerHost, http.DefaultMaxIdleConnsPerHost) fmt.Println(t.IdleConnTimeout, t.TLSHandshakeTimeout) }
- reused GET
- 0.07 ms.
- new TCP
- 0.20 ms, 2.8 times a reused one.
- new TLS
- 2.22 ms, 30 times a reused one.
- held conn
- 1 goroutine and about 9 KB, measured over 1,000 connections.
- idle limit
- 2 per host by default: 374 connections for 1,000 requests, against 33 with a limit of 32.
- drain
- Up to 256 KB and 50 ms on Close, from the net/http source.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1,000 requests, on a busy machine. Use these as orders of magnitude.