CHAPTER 6Advanced HTTP Server Applications

In this chapter, you will learn techniques that will be useful when you are writing production-quality HTTP server applications. You will start by learning about the http.Handler type, and you will use it to share data across handler functions. Then you will learn how to implement common server functionality as middleware. You will learn about the http.HandlerFunc type and use it to define and chain together middleware. You will end the chapter by looking at a strategy to organize your server application and test the various components. Let's get started!

The Handler Type

In this section, you will learn about the http.Handler type — a fundamental mechanism that enables how HTTP server works in Go. You are now familiar with the http.ListenAndServe( ) function that starts an HTTP server. Formally, the signature of this function is as follows:

func ListenAndServe(addr string, handler Handler)

The first argument is the network address on which to listen, and the second object is a value of type http.Handler defined in the net/http package as follows:

type Handler interface {
        ServeHTTP(ResponseWriter, *Request)
}

Thus, the second parameter of the http.ListenAndServe() function can be any object that implements the http.Handler interface. How do we create such an object? You are now familiar with the following pattern for building an HTTP server application:

mux := http.NewServeMux()
// register handlers with mux
http.ListenAndServe(addr, ...

Get Practical Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.