官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 济南市| 齐齐哈尔市| 柳河县| 鄢陵县| 新丰县| 万年县| 偃师市| 平陆县| 耿马| 毕节市| 怀集县| 观塘区| 望城县| 扬中市| 罗城| 连州市| 木里| 绥化市| 刚察县| 鱼台县| 高邑县| 衡南县| 司法| 六安市| 会泽县| 海伦市| 夹江县| 昌黎县| 武平县| 华池县| 顺平县| 翼城县| 漠河县| 睢宁县| 余姚市| 朝阳县| 财经| 洛川县| 西昌市| 驻马店市| 广饶县|