Book Image

Hands-On RESTful Web Services with Go - Second Edition

By : Naren Yellavula
Book Image

Hands-On RESTful Web Services with Go - Second Edition

By: Naren Yellavula

Overview of this book

Building RESTful web services can be tough as there are countless standards and ways to develop API. In modern architectures such as microservices, RESTful APIs are common in communication, making idiomatic and scalable API development crucial. This book covers basic through to advanced API development concepts and supporting tools. You’ll start with an introduction to REST API development before moving on to building the essential blocks for working with Go. You’ll explore routers, middleware, and available open source web development solutions in Go to create robust APIs, and understand the application and database layers to build RESTful web services. You’ll learn various data formats like protocol buffers and JSON, and understand how to serve them over HTTP and gRPC. After covering advanced topics such as asynchronous API design and GraphQL for building scalable web services, you’ll discover how microservices can benefit from REST. You’ll also explore packaging artifacts in the form of containers and understand how to set up an ideal deployment ecosystem for web services. Finally, you’ll cover the provisioning of infrastructure using infrastructure as code (IaC) and secure your REST API. By the end of the book, you’ll have intermediate knowledge of web service development and be able to apply the skills you’ve learned in a practical way.
Table of Contents (16 chapters)

Handling Routing for our REST Services

In this chapter, we will discuss routing for a REST application. To create an API, the first step is to define routes. To define routes, we have to figure out the available system packages in Go. We'll begin this chapter by exploring the basic internal routing mechanism in Go. We then see how to create a custom multiplexer, an entity that matches a given URL to a registered pattern. A multiplexer basically allows a developer to create a route to listen to client requests and attaches handlers that hold the business logic of the application. The ServeMux package is the basic multiplexer provided by Go. We'll then explore a few other frameworks as ServeMux capabilities are very limited.

This chapter also includes the likes of third-party libraries such as httprouter and gorilla/mux. Then, we'll discuss topics such as SQL injection. The crux of this chapter is to teach you how to create elegant HTTP routers in Go using gorilla/mux. We'll also briefly discuss designing a URL shortening service.

We will cover the following topics:

  • Understanding Go's net/http package
  • ServeMux—a basic router in Go
  • Understanding httprouter—a lightweight HTTP router
  • Introducing gorilla/mux—a powerful HTTP router
  • Reader's challenge: an API for URL shortening