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):
- The server receives a client request at a certain path, say
/api. - The server checks if it can handle this request.
- 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.
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access