liveBook · Manning

Http.ResponseWriter

As explained in Learn Go with Pocket-Sized Projects

http.ResponseWriter is a Go interface through which an HTTP handler constructs a response, including its headers, status, and body.

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains write ordering and defaults through handlers and tests, without implementing the interface itself.
Examples
Uses a POST /games JSON response, a plain-text or HTML page, and a controlled test-server response.
What it assumes
Assumes working Go function syntax while introducing ResponseWriter through small HTTP handlers and observable responses.
What you can do after
Build it from scratch: write handler responses with the intended headers and status, then test them with httptest.NewRecorder().
How it connects
Connects HTTP handlers and routers to status codes, JSON encoding, HTML output, logging, and httptest recorders.

Also explained in

Compare how 2 books explain http.ResponseWriter →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.