Skip to content

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.

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, and gofmt.
  • Use Go’s error values, defer, and implicitly satisfied interfaces such as io.Reader and http.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/http that flushes each chunk and answers 502 and 504 correctly.

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:

CommandWhat 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 -raceadds 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.

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 function

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 much
type Writer interface { Write(p []byte) (n int, err error) } // io.Writer: consume p
type Handler interface { ServeHTTP(w ResponseWriter, r *Request) } // http.Handler: answer one request

The 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().

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.

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 ms
defer cancel() // always: frees the timer

Four 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.

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).

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.

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)ClientProxy handler (one goroutine)Upstream
0sends GET /tickstarts; ctx deadline = 0 + 300 = 300
0Do(req) with ctx; waits for headersreceives the request
1headers arrive: copies them, WriteHeader(200)sends 200 OK
20Read returns 1 byte .; Write; Flushwrites .
21receives .
40 … 280receives one . per 20 mssame loopone . per 20 ms
300deadline: Read returns context.DeadlineExceeded; CopyFlush returns; handler returnsits request context is cancelled; it stops
300body 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.DoerrAnswer
upstream answered headers in timenilcopy status, headers, body
client already gone (r.Context().Err() != nil)context.Cancelednothing: nobody is listening
upstream silent until the deadlinewraps context.DeadlineExceeded504
nothing listening on the portconnect: connection refused502

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 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.

Seven requirements lead to the code. Try to write each function before reading it.

  1. 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 New builds the upstream URL from the base plus the incoming path and query, and copies headers in both directions.
  2. 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.
  3. Every forwarded request has a ceiling counted from the start: a deadline, not an idle timeout. That is one context.WithTimeout at the top of the handler, applied to the whole exchange, headers and body.
  4. WithTimeout returns a cancel function that must run on every path out of the handler, so it is deferred immediately.
  5. When Do fails, the cause decides the answer, and the order matters: if the client is gone, answer nothing; if the deadline passed, 504; anything else, 502.
  6. Response headers and the status must be set before the first body byte, so headers are copied, then WriteHeader, then the body.
  7. 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 Read contract: write the n bytes before looking at the error, and treat io.EOF as success.
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 goroutines

New 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.

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 close

A 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.

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.

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.

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.

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:

PitfallSymptomHow the solution avoids it
copying with io.Copy(w, resp.Body) and no flushthe client sees nothing until 4 KiB accumulate or the upstream finishesCopyFlush 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 deadlinecontext.WithTimeout(r.Context(), timeout)
ctx, _ := context.WithTimeout(...) (the cancel function discarded)a timer leaks per requestdefer 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 deadlinea trickling upstream holds the client foreverone WithTimeout at the start of the handler, never reset
answering 502 for every Do errora slow upstream and a dead one look the same to the clientthe 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 bytesthe last chunk is dropped, or a clean end reports an errorCopyFlush writes the n bytes first, then returns nil on io.EOF
setting response headers after WriteHeader or the first Writethey are silently droppedheaders are copied into w.Header() before w.WriteHeader(resp.StatusCode)

Warning: Check r.Context().Err(), not ctx.Err(), to detect a departed client. The derived context is also done at the deadline, so checking it would silently swallow every 504.

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.

  • 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/http package docs (free), including http.Server’s ReadTimeout, WriteTimeout, and IdleTimeout and http.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: -1 for 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.
  • module: a directory tree with a go.mod file, containing packages under one module path.
  • package: one directory of .go files sharing a package name; 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.
  • 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 vet and gofmt are part of everyday Go.
  • Interfaces are satisfied implicitly; http.Handler, io.Reader, and io.Writer are the three a proxy is built from.
  • A goroutine runs a function concurrently and a channel passes values between goroutines; net/http runs 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.ResponseWriter buffers, so streaming means flushing after every write.
  1. Why is the upstream context derived from r.Context() rather than context.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 from Background() would keep the upstream working until the deadline for nobody.

  2. In the switch, why is r.Context().Err() checked before DeadlineExceeded, and why not ctx.Err()?

    Answer

    A client hang-up also makes Do fail, 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.

  3. What would a client see if CopyFlush used io.Copy instead 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.

  4. Why does CopyFlush write buf[:n] before checking err?

    Answer

    The io.Reader contract allows n > 0 together with a non-nil error, including io.EOF on the last chunk. Checking the error first would drop those final bytes.

  5. 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.Read returns context.DeadlineExceeded; CopyFlush returns it; the handler returns and net/http ends the response. No gap between bytes is longer than 20 ms, so an idle timeout would never have fired.