1.6 Go: packages, interfaces, goroutines, channels, context, net/http, testing
Picture a system made of a Python model, a C kernel, and a Rust engine that serves completions over HTTP with no authentication. Anyone who can reach the engine’s port can use it, and nothing stands between a client and a stalled engine. The fix is a gateway in front of the engine, and in AI Engineering that gateway is written in Go, as is every control-plane component after it: the durable workflow engine, the load generator, and the agent SDK.
Concepts from other sections (5)
This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.
- API key: a credential
tl_<id>_<secret>whose public id locates a record and whose secret proves possession. Read more: 10.1 API Keys, Scopes, Model Allowlists, and Tenants in Software Engineering - Interface value: a pair of dynamic type and dynamic value, nil only when both halves are nil. Read more: 17.1 Predicting Go output
- hop-by-hop header: a header that describes one connection only and is not forwarded across a proxy. Read more: 25.1 The tracer gateway in AI Engineering
- last chunk: the chunk that reaches the end of a sequence, the only chunk whose logits are sampled. Read more: 23.4 Chunked prefill (mixed prefill + decode batches) in AI Engineering
- Server-Sent Events (SSE): a one-way, text-only stream of events over a single long-lived HTTP response with
Content-Type: text/event-stream. Read more: Chapter 4: Streaming and SSE in Systems Engineering
A gateway is, at its core, a streaming reverse proxy: it receives a request, makes a second request to the engine, and copies the answer back as it arrives. This section teaches Go by building exactly that, without the API keys and trace headers, so that when you reach the streaming proxy the only new ideas are the gateway’s. The solution is one file, proxy.go, with two functions: New, a streaming HTTP reverse proxy with a deadline, and CopyFlush, the copy loop at its heart. The two signatures and the rules that accompany them are the whole contract.
Go is introduced by comparison with the earlier primers. You should have read HTTP/1.1, JSON, and Server-Sent Events, since this proxy forwards exactly those bytes, and C, whose pointers and dynamic array Go’s slices echo. Every term is defined before it is used. To run the solution’s checks yourself, use go vet and go test -race in a module that contains proxy.go and a test file.
Learning objectives
- Organize Go code into modules and packages, and use
go vet,go test -race, andgofmt.- Use Go’s error values,
defer, and implicitly satisfied interfaces such asio.Readerandhttp.Handler.- Coordinate goroutines with channels and
select, and write tests that synchronize on channels rather than sleeping.- Propagate cancellation and deadlines with
context, and distinguish a deadline from an idle timeout.- Build a streaming reverse proxy with
net/httpthat flushes each chunk and answers 502 and 504 correctly.
Modules, packages, and the toolchain
Section titled “Modules, packages, and the toolchain”A module is a directory tree with a go.mod file at its root. go.mod names the module path (for example tinyllm for the system’s Go code, or lang06 for this primer) and the Go version. A package is one directory of .go files that all begin with the same package <name> line. A package is imported by its import path: the module path plus the directory, so the directory go/gateway/proxy of module tinyllm is imported as "tinyllm/gateway/proxy" and used as proxy.NewProxy.
A name is exported (visible to other packages) exactly when it starts with an upper-case letter: New and CopyFlush are exported, copyHeaders is not. There are no public or pub keywords.
The toolchain is part of the language’s culture, and the solution is go vet clean. These are the commands you use:
| Command | What it does |
|---|---|
go build ./... | compiles every package under the current directory (./... means “this directory and below”) |
go vet ./... | runs static checks for real bugs: a context’s cancel function never called, a Printf format that does not match its arguments, a struct copied with its lock |
go test ./... | compiles each package with its _test.go files and runs every func TestXxx(t *testing.T) |
go test -race | adds the race detector: two goroutines touching the same memory without synchronization, with at least one writing, make the test fail |
gofmt -l . | lists files not in the one standard layout; Go code is never formatted by hand |
Unlike Python, an unused import or an unused local variable is a compile error. Unlike C, there are no header files: a package’s exported names are its interface.
Values, errors, and defer
Section titled “Values, errors, and defer”Go is statically typed with type inference: x := 3 declares an int. A struct is a C struct with methods attached. A slice ([]byte) is a pointer, a length, and a capacity over an array: exactly the dynamic array from the C primer. buf[:n] is a slice of the first n bytes that shares the same memory; nothing is copied.
Functions return several values. Failure is a value of the built-in interface type error, returned last, never thrown:
n, err := r.Read(buf)if err != nil { return total, err}errors.Is(err, target) reports whether err is target or wraps it, which matters because errors are often wrapped with context (fmt.Errorf("read upstream: %w", err)). A few errors are sentinels, values you compare against: io.EOF means “the stream ended normally”, which is success, not failure.
defer f() schedules f to run when the surrounding function returns, whichever return it takes. It is how Go closes response bodies and calls cancel functions:
resp, err := client.Do(req)if err != nil { return}defer resp.Body.Close() // runs on every path out of the functionInterfaces
Section titled “Interfaces”An interface type lists methods. Any type that has those methods satisfies the interface, with no declaration that it does (Rust needs impl Trait for Type; Go does not). Anything with a Read([]byte) (int, error) method is an io.Reader. Three interfaces carry everything in this section, and a proxy is built from them:
type Reader interface { Read(p []byte) (n int, err error) } // io.Reader: fill p, report how muchtype Writer interface { Write(p []byte) (n int, err error) } // io.Writer: consume ptype Handler interface { ServeHTTP(w ResponseWriter, r *Request) } // http.Handler: answer one requestThe Read contract is worth reading slowly, because every streaming bug starts here: Read may return fewer bytes than len(p), and it may return n > 0 and a non-nil error in the same call. So the correct loop writes the n bytes first and then looks at the error.
http.HandlerFunc is a function type with a ServeHTTP method that calls the function itself, so any func(w http.ResponseWriter, r *http.Request) becomes a Handler by conversion: http.HandlerFunc(myFunc). That is the usual way to return a handler that closes over configuration, as New does.
An interface value can be asked what else it is. http.ResponseWriter is an interface; the concrete writer net/http passes in also has a Flush() method. The modern way to reach it, even through wrappers, is a response controller: http.NewResponseController(w).Flush().
Goroutines and channels
Section titled “Goroutines and channels”Interfaces describe what code can do; goroutines describe when it runs. go f(x) starts f(x) in a new goroutine: a function running concurrently with its caller, scheduled by the Go runtime onto OS threads. Goroutines are cheap (a few KiB of stack), so net/http starts one per incoming request. A handler is therefore concurrent code even when it looks sequential: it runs on many goroutines at once, which is why its tests run under the race detector.
A channel is a typed pipe between goroutines that both passes values and synchronizes. ch := make(chan string) makes an unbuffered channel: a send ch <- v blocks until another goroutine receives <-ch, so the two meet at that point. make(chan string, 1) holds one value without a waiting receiver. close(ch) says no more values will come; every receive on a closed channel returns at once, which makes close a broadcast. select waits on several channel operations and runs whichever is ready first:
select {case got := <-result: // the work finished use(got)case <-time.After(3 * time.Second): // a channel that receives one value after 3 s t.Fatal("gave up after 3 s")}Good proxy tests are built from exactly these pieces: a fake upstream blocks on a channel until the test has seen the first chunk, then the test closes the channel to let it continue. Nothing in them sleeps for a fixed time.
context: cancellation and deadlines
Section titled “context: cancellation and deadlines”Goroutines need a way to be told to stop, and that is context. A context.Context carries three things down a call chain: a Done channel that is closed when the work should stop, the error that says why (context.Canceled or context.DeadlineExceeded), and optionally a deadline, an absolute point in time. Contexts form a tree: a child is cancelled when its parent is.
ctx, cancel := context.WithTimeout(parent, 300*time.Millisecond) // deadline = now + 300 msdefer cancel() // always: frees the timerFour facts about contexts decide the proxy’s design. First, r.Context() is the context of an incoming request; net/http cancels it when the client disconnects, so deriving from it is what makes a client hang-up reach the upstream. Second, context.Background() is the empty root, and using it for the upstream request cuts the link to the client. Third, WithTimeout returns a cancel function, and forgetting to call it leaks a timer until the deadline; go vet reports it (lostcancel). Fourth, a deadline is fixed when it is created, while an idle timeout restarts after every byte. They behave differently on an upstream that trickles one byte every 20 ms: an idle timeout of 300 ms never fires, a deadline of 300 ms always does.
net/http: one request, two roles
Section titled “net/http: one request, two roles”As a server, net/http calls a Handler once per request, on its own goroutine. The handler answers through the http.ResponseWriter, in a fixed order: set headers with w.Header().Set(...), then the status with w.WriteHeader(code), then the body with w.Write(...). The first Write sends status 200 if WriteHeader was not called, and headers set after that are ignored.
The writer buffers the body (4 KiB by default) and sends it when the buffer fills or the handler returns. For an ordinary response that is efficient. For a stream it is wrong: a 10-byte chunk sits in the buffer until 4086 more bytes arrive. Flush sends what is buffered now. Streaming therefore means flushing after every write; a proxy that buffers holds the first chunk until the upstream sends more, which for a token stream may be never.
As a client, you build a request with http.NewRequestWithContext(ctx, method, url, body) and send it with client.Do(req). Do returns when the response headers have arrived; the body is a stream (resp.Body, an io.ReadCloser) that the caller reads and must close. If ctx is cancelled or its deadline passes, Do (or a later resp.Body.Read) returns an error that errors.Is matches against context.DeadlineExceeded or context.Canceled.
A reverse proxy is both roles at once: a server for the client and a client for the upstream. Two status codes name its own failures: 502 Bad Gateway (the upstream could not be reached or answered with garbage) and 504 Gateway Timeout (the upstream did not answer in time).
testing
Section titled “testing”A test is func TestXxx(t *testing.T) in a file ending _test.go. t.Fatalf fails and stops the test, t.Helper() makes a failure point at the caller, and t.Cleanup(f) runs f when the test ends, last registered first. A test file may be in the package it tests or in <pkg>_test, a separate package that sees only exported names; tests of a contract use the second form, so they test only exported behavior.
net/http/httptest.NewServer(handler) starts a real HTTP server on a free local port and returns its URL. Both ends of a proxy test are real servers: a fake upstream and the proxy in front of it.
A build tag is a first line //go:build primer; the file is compiled only when the tag is given (go test -tags primer). Tests for this primer can carry it so they stay out of the system’s own Go module.
Working it by hand
Section titled “Working it by hand”Follow one request through a proxy built with New("http://127.0.0.1:9000", 300*time.Millisecond). The upstream on port 9000 answers GET /tick with status 200 and then writes . and flushes every 20 ms, forever. The timeline is:
| Time (ms) | Client | Proxy handler (one goroutine) | Upstream |
|---|---|---|---|
| 0 | sends GET /tick | starts; ctx deadline = 0 + 300 = 300 | |
| 0 | Do(req) with ctx; waits for headers | receives the request | |
| 1 | headers arrive: copies them, WriteHeader(200) | sends 200 OK | |
| 20 | Read returns 1 byte .; Write; Flush | writes . | |
| 21 | receives . | ||
| 40 … 280 | receives one . per 20 ms | same loop | one . per 20 ms |
| 300 | deadline: Read returns context.DeadlineExceeded; CopyFlush returns; handler returns | its request context is cancelled; it stops | |
| 300 | body ends after 14 or 15 dots |
Count the dots: ticks happen at 20, 40, …, 280 ms inside the window, which is 280 / 20 = 14 ticks, and the 300 ms tick races the deadline, so the client sees 14 or 15 dots. A correct proxy guarantees only that some arrive and that the body ends long before the 1.5 s the test is willing to wait. An idle timeout of 300 ms would never end this body, because no gap is longer than 20 ms.
The same handler can fail in three ways, and they must be decided in this order:
Situation at client.Do | err | Answer |
|---|---|---|
| upstream answered headers in time | nil | copy status, headers, body |
client already gone (r.Context().Err() != nil) | context.Canceled | nothing: nobody is listening |
| upstream silent until the deadline | wraps context.DeadlineExceeded | 504 |
| nothing listening on the port | connect: connection refused | 502 |
The client check must come before the deadline check: a client that hangs up makes Do fail too, and answering it would write to a closed connection.
The interface
Section titled “The interface”The solution is one file, primers/lang.06/proxy.go, in package proxy, importing only the standard library:
// New returns a handler that forwards every request to upstream (a base URL such as// "http://127.0.0.1:8080") with the same method, path, query, headers, and body, and// streams the upstream's status, headers, and body back, flushing each chunk as it// arrives. Every forwarded request has a deadline of timeout from the moment the// handler starts: no upstream headers by then is 504; a deadline mid-body ends the// body; a client that goes away cancels the upstream request; an unreachable// upstream is 502.func New(upstream string, timeout time.Duration) http.Handler
// CopyFlush copies src to w until src is exhausted, flushing w after every chunk it// writes. It returns the bytes written and the error that stopped it: nil when src// ended with io.EOF.func CopyFlush(w http.ResponseWriter, src io.Reader) (int64, error)A correct solution passes go vet, and its tests pass under go test -race.
Building it step by step
Section titled “Building it step by step”Seven requirements lead to the code. Try to write each function before reading it.
- A proxy must be invisible: the upstream sees the client’s method, path, query, headers, and body; the client sees the upstream’s status, headers, and body. So
Newbuilds the upstream URL from the base plus the incoming path and query, and copies headers in both directions. - The upstream request must stop when the client stops caring.
r.Context()is cancelled when the client disconnects, so the upstream request’s context must be derived from it. - Every forwarded request has a ceiling counted from the start: a deadline, not an idle timeout. That is one
context.WithTimeoutat the top of the handler, applied to the whole exchange, headers and body. WithTimeoutreturns a cancel function that must run on every path out of the handler, so it is deferred immediately.- When
Dofails, the cause decides the answer, and the order matters: if the client is gone, answer nothing; if the deadline passed, 504; anything else, 502. - Response headers and the status must be set before the first body byte, so headers are copied, then
WriteHeader, then the body. - A stream must reach the client as it arrives, so the body is copied chunk by chunk with a flush after each write, honoring the
Readcontract: write thenbytes before looking at the error, and treatio.EOFas success.
Building the upstream request
Section titled “Building the upstream request”func New(upstream string, timeout time.Duration) http.Handler { base := strings.TrimRight(upstream, "/") // "http://h:8080/" + "/x" must not give "//x" return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // steps 2 and 3: a child of the client's context, with a deadline from now ctx, cancel := context.WithTimeout(r.Context(), timeout) defer cancel() // step 4: every path out frees the timer
target := base + r.URL.EscapedPath() // the path as sent, percent-encoding kept if r.URL.RawQuery != "" { target += "?" + r.URL.RawQuery // the query as sent, not re-encoded } req, err := http.NewRequestWithContext(ctx, r.Method, target, r.Body) // the body streams through if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } req.ContentLength = r.ContentLength // keep the framing the client chose req.Header = r.Header.Clone() // a copy: never share a map across goroutinesNew is called once; it returns a closure over base and timeout, and http.HandlerFunc turns that closure into a Handler. Everything inside the closure runs per request, on that request’s goroutine. Passing r.Body as the upstream body means request bodies are streamed too, never read into memory. EscapedPath and RawQuery forward exactly what the client sent; decoding and re-encoding could change the bytes the upstream sees.
Deciding the failure
Section titled “Deciding the failure” resp, err := http.DefaultClient.Do(req) // returns once upstream headers arrive switch { case err == nil: // go on to copy case r.Context().Err() != nil: return // the client left; there is nobody to answer case errors.Is(err, context.DeadlineExceeded): http.Error(w, "upstream timed out", http.StatusGatewayTimeout) // 504 return default: http.Error(w, "upstream unreachable: "+err.Error(), http.StatusBadGateway) // 502 return } defer resp.Body.Close() // only after err == nil is there a body to closeA switch with no expression tests its cases top to bottom, which encodes step 5’s order directly. The client check uses r.Context(), not ctx: ctx is also done when the deadline passes, so checking it would turn every timeout into a silent return instead of a 504. errors.Is sees through the *url.Error wrapper Do returns.
Copying the response
Section titled “Copying the response” for k, vs := range resp.Header { for _, v := range vs { w.Header().Add(k, v) // Add, not Set: keep every value of repeated headers } } w.WriteHeader(resp.StatusCode) // step 6: status after headers, before the body _, _ = CopyFlush(w, resp.Body) })}The result of CopyFlush is discarded on purpose: once the status line is sent, the proxy cannot report an error to the client any more, and the cause is already visible to it as a truncated body. When the deadline passes mid-body, resp.Body.Read returns the context error, CopyFlush returns, the handler returns, and net/http ends the response, which is the 14 or 15 dots of the timeline.
The copy loop
Section titled “The copy loop”func CopyFlush(w http.ResponseWriter, src io.Reader) (int64, error) { rc := http.NewResponseController(w) // reaches Flush even through wrapping writers buf := make([]byte, 32*1024) // one buffer, reused for every chunk var total int64 for { n, err := src.Read(buf) if n > 0 { // step 7: bytes first, even if err != nil m, werr := w.Write(buf[:n]) // a slice of the bytes read: no copy total += int64(m) if werr != nil { return total, werr // the client is gone: stop reading upstream } if ferr := rc.Flush(); ferr != nil && !errors.Is(ferr, http.ErrNotSupported) { return total, ferr } } if errors.Is(err, io.EOF) { return total, nil // a clean end is success } if err != nil { return total, err // e.g. context.DeadlineExceeded mid-body } }}Each iteration handles whatever one Read returned, whether that is one byte or 32 KiB, so the client receives the upstream’s chunks at the upstream’s pace. A writer that cannot flush (http.ErrNotSupported, as in some test recorders) is not an error: the bytes are still written, just not pushed early. With a reader that returns a, b, c one byte at a time and then io.EOF, the loop writes and flushes three times and returns (3, nil); with one that returns ab and then an error, it returns (2, that error).
The full solution is proxy.go.
Why this design
Section titled “Why this design”In cost, there is one goroutine per request (from net/http), one 32 KiB buffer per response, and a flush per upstream chunk. The latency added is one read and one write per chunk.
The loop is hand-written rather than io.Copy because io.Copy has no flush, so a stream would sit in the ResponseWriter’s buffer. httputil.ReverseProxy with FlushInterval: -1 does the same job in production; writing it once shows what that setting means. A deadline, rather than an idle timeout, bounds the total time and resources one request can hold, even against an upstream that trickles bytes; the cost is that a legitimately long stream is cut at the ceiling, which the caller chooses through timeout. http.DefaultClient, rather than a configured client, is enough for a primer, but it has no connection limits and shares state process-wide; the real gateway builds its own client. And one tradeoff is accepted deliberately: hop-by-hop headers (Connection, Keep-Alive, Transfer-Encoding) are forwarded as they are, whereas a production proxy removes them, as ReverseProxy does.
What can go wrong
Section titled “What can go wrong”The tests drive the proxy with real servers at both ends. Method, path, query, headers, and body must reach the upstream, and status 201, a header, and the body must come back, because a gateway must be invisible to both sides. The first chunk must reach the client while the upstream is still holding the second, which is token streaming through a gateway. An upstream that sends no headers within 100 ms must produce a 504 and have its request cancelled, so a stalled engine does not stall the client. A stream that stalls after one chunk must end at the deadline, keeping the chunk, because streams have a ceiling, and the trickling upstream from the timeline must still end at the deadline, because it is a deadline and not an idle timeout. Cancelling the client’s request must cancel the upstream’s within 3 s, so abandoned completions stop generating. A refused connection must give 502, the gateway’s “engine down” answer, which the real gateway turns into 503 no_capacity. And CopyFlush on its own must return (3, nil) with at least 3 flushes for one-byte reads, and (2, that error) for a reader failing after ab, since it is the copy loop the gateway reuses.
The mistakes that break those checks are these:
| Pitfall | Symptom | How the solution avoids it |
|---|---|---|
copying with io.Copy(w, resp.Body) and no flush | the client sees nothing until 4 KiB accumulate or the upstream finishes | CopyFlush calls rc.Flush() after every write |
context.WithTimeout(context.Background(), ...) instead of r.Context() | a client that hangs up leaves the upstream working until the deadline | context.WithTimeout(r.Context(), timeout) |
ctx, _ := context.WithTimeout(...) (the cancel function discarded) | a timer leaks per request | defer cancel() right after WithTimeout; go vet’s lostcancel check would flag the omission |
a per-read idle timeout (a timer reset on every Read) instead of a deadline | a trickling upstream holds the client forever | one WithTimeout at the start of the handler, never reset |
answering 502 for every Do error | a slow upstream and a dead one look the same to the client | the switch after Do tests errors.Is(err, context.DeadlineExceeded) before the 502 default |
treating io.EOF as a failure, or checking err before writing the n bytes | the last chunk is dropped, or a clean end reports an error | CopyFlush writes the n bytes first, then returns nil on io.EOF |
setting response headers after WriteHeader or the first Write | they are silently dropped | headers are copied into w.Header() before w.WriteHeader(resp.StatusCode) |
Warning: Check
r.Context().Err(), notctx.Err(), to detect a departed client. The derived context is also done at the deadline, so checking it would silently swallow every 504.
Where this leads
Section titled “Where this leads”In AI Engineering, the streaming proxy is this proxy plus an API key, trace context, and contract errors, and the SSE streaming proxy upgrades it so abandoned completions stop generating. The append-only event log of the durable engine uses goroutines, channels, and testing, and the agent SDK’s OpenAI-compatible provider reads SSE through net/http. In AI Engineering, the open-loop load generator combines goroutines, context deadlines, and net/http clients. The next section, Containers and Kubernetes, packages these services to run in a cluster.
Further reading
Section titled “Further reading”- A Tour of Go (free) and Effective Go (free).
- The Go Memory Model (free).
- Donovan and Kernighan, The Go Programming Language, chapters 7 to 9.
net/httppackage docs (free), includinghttp.Server’sReadTimeout,WriteTimeout, andIdleTimeoutandhttp.Client.Timeout: server-side limits per connection and a client-side whole-exchange deadline.httputil.ReverseProxy(free): hop-by-hop header removal,X-Forwarded-For,FlushInterval: -1for streaming, an error handler, and buffer pools.errgroup(free): a group of goroutines that share a context and return the first error.- Go race detector (free): the ThreadSanitizer algorithm under
-race.
Key terms
Section titled “Key terms”- module: a directory tree with a
go.modfile, containing packages under one module path. - package: one directory of
.gofiles sharing apackagename; capitalized names are exported. - interface: a method set that any type with those methods satisfies implicitly.
- goroutine: a function running concurrently, scheduled by the Go runtime.
- channel: a typed pipe that passes values between goroutines and synchronizes them.
- context: a value carrying a cancellation signal, its reason, and an optional deadline down a call tree.
- deadline: a fixed point in time after which work is cancelled, unlike an idle timeout that restarts on activity.
- reverse proxy: a server that forwards each request to an upstream and relays the response.
Summary
Section titled “Summary”- A Go module is a tree of packages; a package is one directory; a name is exported when it starts with a capital letter, and
go vetandgofmtare part of everyday Go. - Interfaces are satisfied implicitly;
http.Handler,io.Reader, andio.Writerare the three a proxy is built from. - A goroutine runs a function concurrently and a channel passes values between goroutines;
net/httpruns every request in its own goroutine, so a handler is concurrent code. - A context carries cancellation and a deadline down a call tree; a deadline is a point in time, not an idle timeout, and its cancel function must always be called.
http.ResponseWriterbuffers, so streaming means flushing after every write.
Review questions
Section titled “Review questions”-
Why is the upstream context derived from
r.Context()rather thancontext.Background()?Answer
r.Context()is cancelled when the client disconnects. A child of it inherits that cancellation, so the upstream request is cancelled too and the engine stops generating. A context fromBackground()would keep the upstream working until the deadline for nobody. -
In the
switch, why isr.Context().Err()checked beforeDeadlineExceeded, and why notctx.Err()?Answer
A client hang-up also makes
Dofail, and writing a 504 to a closed connection is pointless, so that case is decided first.ctx.Err()would be non-nil for the deadline as well, which would swallow every 504;r.Context()is cancelled only by the client. -
What would a client see if
CopyFlushusedio.Copyinstead of its loop?Answer
Nothing until the
ResponseWriter’s buffer filled (about 4 KiB) or the upstream finished. For a token stream of small events, that means the whole answer at the end instead of token by token. -
Why does
CopyFlushwritebuf[:n]before checkingerr?Answer
The
io.Readercontract allowsn > 0together with a non-nil error, includingio.EOFon the last chunk. Checking the error first would drop those final bytes. -
The upstream answers headers at 1 ms and then sends a byte every 20 ms forever. With
timeout = 300ms, when does the client’s body end, and what ends it?Answer
At about 300 ms, after 14 or 15 bytes. The deadline set when the handler started fires;
resp.Body.Readreturnscontext.DeadlineExceeded;CopyFlushreturns it; the handler returns andnet/httpends the response. No gap between bytes is longer than 20 ms, so an idle timeout would never have fired.