Home > Articles

Go HTTP Servers

  • Print
  • + Share This
This chapter is from the book

Working with Handler Functions

While the Go router maps routes to functions, it is the handler functions that define how a request is handled and the response that is returned to the client. Many programming languages and web frameworks follow the pattern of passing a request and response through functions before returning the response. Go is similar in this respect. Handler functions are responsible for these common tasks:

  • Reading or writing headers

  • Examining the type of a request

  • Fetching data from a database

  • Parsing request data

  • Authentication

Handler functions have access to the Request and the Response, so a common pattern is to complete everything needed for the request before writing the response back to the client. Once the response is written, no further processing on the response can take place. In the following example, the response is sent using the Write method. On the next line, a header is set on the response to be written. As the response has already been written, this will have no effect, but the code will compile. The key point: Write the response last.

func helloWorld(w http.ResponseWriter, r *http.Request) {
     w.Write([]byte("Hello World\n"))
     // This has no effect, as the response is already written
     w.Header().Set("X-My-Header", "I am setting a header!")
  • + Share This
  • 🔖 Save To Your Account