An HTTP handler receives an http.ResponseWriter alongside the request. The writer is where the handler builds the response: set headers, choose a status, and write the body. A function with the signature func(http.ResponseWriter, *http.Request) can be registered with a router using HandleFunc. section 8.2.1
The order of writes matters:
- Use w.Header().Set before sending the response when a header needs an explicit value, such as Content-Type: application/json. section 8.2.1
- Call w.WriteHeader(status) before writing the body if the response should not use 200 OK. Otherwise, Write supplies that default status; it also handles Content-Type and Content-Length in most cases. section 8.2.1 section 11.1.1
- Write the body with w.Write, io.WriteString, or an encoder that writes to w. Once writing has started, a later WriteHeader cannot change the status. section 8.2.1 section 11.1.1
Return a newly created game
A POST /games handler can set Content-Type to application/json, call w.WriteHeader(http.StatusCreated), then call json.NewEncoder(w).Encode(apiGame). If encoding fails after the header is sent, log the failure: the handler can no longer replace the response with a different error status. Test the handler with httptest.NewRecorder(), checking its status, header, and JSON body. section 8.2.1
Listing 8.11 newgame/handler.go: Returning a Game response
func Handle(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json") #1
w.WriteHeader(http.StatusCreated)
apiGame := api.GameResponse{} #2
err := json.NewEncoder(w).Encode(apiGame) #3
if err != nil { #4
// The header has already been set. Nothing much we can do here.
log.Printf("failed to write response: %s", err)
}
}
The handler listing shows header, status, and JSON body writes in sequence, followed by logging for an encoding failure. section 8.2.1
The same interface is useful in tests of HTTP clients: an httptest server’s handler can write a controlled response to its ResponseWriter, allowing the client to be tested without calling the real service. section 6.5.4

