Prerequisite: The net/http package
- [Instructor] In this section, we will have a brief recap of the net/http package. We'll use the HTTP package to build a demo app later on. If you are already familiar with it, feel free to skip onto the next section. The HTTP package provides client and server implementations. It is available in the Go standard library. It is an important and easy-to-use package, and it is one of the reasons that Go is a popular solution for building web applications. You can see the documentation on the official Go docs. On the internet, information is mostly exchanged via HTTP. The exchange begins with the client sending out an HTTP request to the server to ask for information. If the server recognizes the request, it begins processing it by invoking any backend code required to fulfill the request. The invoked functions are typically called request handlers. Once the backend processing completes, the server finishes the information exchange by wrapping the information into an HTTP response and sending it back to the client. The HTTP package makes our lives easier. All client request routing and HTTP client and server internals are implemented for us. We only need to supply the backend handlers. Let's have a quick look at a simple implementation example. The simple code snippet is enough to start the server and configure an HTTP end point. The http.HandleFunc on line 10 configures the server to handle all requests to the hello URL path with a hello function. This allows us to map which backend functionality should be invoked to fulfill the request. The call to ListenAndServe on line 13 tells the server to listen on the TCP network address 8080. This function blocks, keeping the server up alive to receive requests. Finally, on line 17, we write to an HTTP response writer to send data to the HTTP client. Let's run this code to see it in action. I will run the server using go run server.go. As we can see from the terminal, the server successfully starts up and listens on port 8080. Now let's go to Postman and send a get request to the local 8080/hello endpoint. The server responds with, "Hello world!" As we have seen, Go's HTTP package is easy to use. We will make extensive use of it later on.