8 Building an HTTP server
This chapter covers
- Using built-in routing via HTTP verbs and path variables
- Hardening a web server with timeout options
- Using middleware and context to prevent code duplication
- The basics of accepting header, cookie, and form data
- Processing other types of request data
- Reducing code duplication through middleware
In the previous chapters we examined some critical building blocks necessary for designing production-ready applications. We have looked at testing and debugging, concurrency, and in chapter 7, networking and file access. We’ll build on the networking aspect in this chapter as we work toward building web applications that can hold up to real world requirements and traffic. We begin by going over the basics of routing and from there move into multiplexers and routers, so we can better match endpoints we want and create responses from the right handlers. We’ll also build middleware to capture common tasks that might otherwise create code duplication or spaghetti logic in our web handlers.
While Go’s http package in the standard library is simple by design and though the tools provided can get us high-performance web servers out of the box, it’s also created with the kind of building block style that encourages extending it. Creating an HTTP server is a matter of a few lines of Go, but building one that handles real world scenarios requires the developer to do some planning and careful construction of these building blocks.