http.ResponseWriter is the response side of a Go HTTP handler. A server passes it with *http.Request to ServeHTTP, and the handler uses it to construct the client response. Header sets response headers, WriteHeader sets the status code, and Write sends body bytes. Set headers and status before writing the body; if no status is set first, writing produces the default 200 OK response. section 8.3
A minimal health response
A health handler can pass its ResponseWriter to fmt.Fprintln because ResponseWriter is also a Writer. Writing "OK" is enough to return a successful 200 response without an explicit WriteHeader call, making a small endpoint useful for availability checks. section 8.3.1
ResponseWriter also makes handlers easy to test: supply an httptest.ResponseRecorder and a request, call the handler directly, then inspect the recorded status and body. The recorder implements ResponseWriter, so production handler code needs no special testing branch. section 8.7 section 8.7.1
The base interface stays small, while concrete response writers may offer optional behavior. Type-assert http.Flusher before flushing buffered data; related optional interfaces include http.Pusher and http.Hijacker. Middleware that wraps a ResponseWriter can accidentally hide such capabilities, so an Unwrap method can expose the original writer when that behavior is required. section 9.4.1 section 9.8.2
Figure 8.6 The http.Server routes incoming HTTP requests to its http.Handler by calling the Handler’s ServeHTTP method, passing an http.ResponseWriter and http.Request. Then the Handler can use the ResponseWriter to respond to clients via the Server.
Follow the request path from http.Server to a handler and back through its ResponseWriter. section 8.3
Listing 9.27 Unwrapping ResponseWriters (link/kit/hio/request.go)
// MaxBytesReader is like [http.MaxBytesReader], but unwraps the
// original [http.ResponseWriter] if it's wrapped.
func MaxBytesReader(
w http.ResponseWriter, rc io.ReadCloser, max int64,
) io.ReadCloser {
type unwrapper interface { #1
Unwrap() http.ResponseWriter #1
} #1
for { #2
v, ok := w.(unwrapper) #3
if !ok {
break #4
}
w = v.Unwrap() #5
}
return http.MaxBytesReader(w, rc, max)
}
Inspect a helper that repeatedly unwraps middleware layers before passing the original writer to MaxBytesReader. section 9.8.2

