What is middleware? 

Middleware is an entity that hooks into a server's request/response processing. The middleware can be defined in many components. Each component has a specific function to perform. Whenever we define the handlers for our URL patterns (as in the last chapter), the request hits the handler and executes the business logic. So virtually all middleware should perform these functions in order:

  1. Process the request before hitting the handler (function)
  2. Process the handler function
  3. Process the response before giving it to the client

We can see the previous points in the form of a visual illustration:

If we observe the diagram carefully, the journey of the request starts with the client. In an application with no middleware, a request reaches the API server and will get handled by some function handler. The response is immediately sent back from the server and the client receives it. But in applications with middleware, it passes through a set of stages, like logging, authentication, session validation, and so on, and then proceeds to the business logic. This is to filter the wrong requests from interacting with the business logic. The most common use cases are:

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

With the help of middleware, we can keep the housekeeping work, like authentication, in its proper place. Let us create a basic middleware and tamper an HTTP request in Go.

Middleware functions should be defined when a piece of code needs to be executed for every request or subset of HTTP requests. Without them, we need to duplicate the logic in each and every handler.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.140.196.244