Hands-On RESTful Web Services with Go
上QQ阅读APP看书,第一时间看更新

What is middleware? 

Middleware is an entity that hooks into a server's request/response life cycle. The middleware can be defined in many components. Each component has a specific function to perform. Whenever we define handlers for URL patterns (as in Chapter 2, Handling Routing for our REST Services), a handler executes some business logic for every incoming request. But middleware, as the name specifies, sits between a request and the handler, or between a handler and a response. So, virtually every middleware can perform these functions:

  • Process the request before reaching the handler (function)
  • Pass the modified request to the handler function (execute some business logic)
  • Process the response coming from the handler
  • Pass the modified response to the client

We can see the previous points in the form of a visual illustration, as shown in the following diagram:

If we observe the diagram carefully, the journey of a request starts from the client. The request first reaches a middleware called AUTH MIDDLEWARE and is then forwarded to a FUNCTION HANDLER. Once a response is generated from a handler, it is then forwarded to another middleware called CUSTOM MIDDLEWARE that can modify the response.

In an application with no middleware, a request reaches the API server and gets handled by a function handler directly. The response is immediately sent back from the server, and the client receives it. But in applications with middleware configured to a function handler, it can pass through a set of stages, such as logging, authentication, session validation, and so on, and then proceeds to the business logic. This is to filter the requests from interacting with the business logic. The most common use cases are as follows:

  • Use a logger to log each and every request for a REST API
  • Validate the session of the user and keep the communication alive
  • Authenticate the user, if not identified
  • Attach properties to responses while serving the client

With the help of middleware, we can do any housekeeping work, such as authentication, in its proper place. Let's create a basic middleware and tamper an HTTP request in Go.

Middleware functions can be handy when many function handlers have the same business logic to execute.