CHAPTER 5Building HTTP Servers

In this chapter, you will dive into the basics of writing HTTP servers. You will learn how handler functions work, discover more about processing requests, and study how to read and write streaming data. You scratched the surface of these topics a bit in the previous chapter. Now it's time to dive in.

Your First HTTP Server

The net/http package gives us the building blocks for writing an HTTP server. A server running on your computer, available at http://localhost:8080, would process a request as follows (see Figure 5.1):

  1. The server receives a client request at a certain path, say /api.
  2. The server checks if it can handle this request.
  3. If the answer is yes, the server calls a handler function to process the request and return the response. If not, it returns an HTTP error as a response to the client.
Schematic illustration of the request processing by an HTTP server.

Figure 5.1: Request processing by an HTTP server

Listing 5.1 shows the simplest web server that you can write.

The ListenAndServe() function in the net/http package starts an HTTP server at a given network address. It is a good idea to make this address ...

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.