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)

Adding logging to microservices

Logging is a crucial aspect of microservices. We can write middleware to capture all requests and responses going into and out of a service. Even for a client, we can capture logs while making RPC calls to a service.

Go Micro is a lean framework and doesn't enforce logging by default. We can easily wrap a service handler with our own custom logger. For example, in the encryptService example, we have a file called handlers.go.

In order to activate logging for each request in a custom format, we have to define a wrapper, and then link it to the service. As an example, if we have to log every incoming encryption request, follow these steps:

  1. Create a new wrapper function. It takes Context, Request, and Response as arguments. Here, we just print the time of the request arrival, like this:
func logWrapper(fn server.HandlerFunc) server.HandlerFunc...