Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Networking and the Web

Go http.ResponseWriter interface

Reference for Go http.ResponseWriter: set headers, write the status code and body in the right order, sniff content types, flush, stream and use ResponseController.

http.ResponseWriter is the interface a handler uses to build an HTTP response. The server passes one to every call of ServeHTTP, and whatever you do with it becomes the status line, the headers and the body that the client receives. It has only three methods: Header, Write and WriteHeader.

The order matters. Headers are sent together with the status code, so you must change Header() before the first call to Write or WriteHeader. After that point, header changes are silently ignored.

Go
func hello(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
	w.WriteHeader(http.StatusCreated)
	fmt.Fprintln(w, "created")
}

Try it

Go Order of headers, status and body

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Flushing a streamed response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
type ResponseWriter interface {
	Header() http.Header
	Write([]byte) (int, error)
	WriteHeader(statusCode int)
}
Method Description
Header() Returns the map of headers that will be sent. Modify it before WriteHeader or the first Write.
Write(b) Writes body bytes. If WriteHeader has not been called, it first sends status 200. Returns the number of bytes written and any network error.
WriteHeader(code) Sends the status code and the headers collected so far. code must be a valid status (100 to 999).

Errors and edge cases: a second WriteHeader call is ignored and the server logs superfluous response.WriteHeader call. Informational 1xx codes (such as 103 Early Hints) may be sent several times before the final status. Writing a body for a HEAD request or for status 204 and 304 fails with http.ErrBodyNotAllowed.

Usage notes

  • Implicit 200. If you never call WriteHeader, the first Write sends 200 OK. If you write nothing at all, the client also gets 200 with an empty body.
  • Content type sniffing. When Content-Type is not set, the server looks at the first 512 bytes with http.DetectContentType. Set the header yourself for JSON, CSS and anything where a wrong guess matters.
  • Helpers. http.Error sets a plain-text content type, X-Content-Type-Options: nosniff, the status and the message. http.Redirect, http.NotFound, http.SetCookie and http.ServeFile also take a ResponseWriter. Call return after them, since they do not stop your handler.
  • Optional interfaces. The concrete writer often also implements http.Flusher, http.Hijacker, io.ReaderFrom and io.StringWriter. Since Go 1.20 prefer http.NewResponseController(w), which offers Flush, Hijack, SetReadDeadline and SetWriteDeadline and unwraps middleware wrappers that implement Unwrap() http.ResponseWriter.
  • Wrapping. Middleware that records the status code wraps the writer in its own struct. Forward Unwrap() so ResponseController keeps working, because embedding alone hides the optional methods.
  • Do not write after the handler returns. The writer is only valid during ServeHTTP. Using it from a goroutine that outlives the handler is a bug.
  • Trailers. Declare them with w.Header().Set("Trailer", "X-Sum") before writing, set the value after the body, or use keys prefixed with http.TrailerPrefix.
  • Large bodies. Write buffers a few kilobytes. For streaming (server-sent events, progress), call Flush after each message.