- Hands-On RESTful Web Services with Go
- Naren Yellavula
- 370字
- 2021-06-24 17:04:28
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.
- 現代C++編程:從入門到實踐
- Getting Started with React
- Getting started with Google Guava
- 零起步玩轉掌控板與Mind+
- Oracle 12c中文版數據庫管理、應用與開發實踐教程 (清華電腦學堂)
- KnockoutJS Starter
- C語言程序設計同步訓練與上機指導(第三版)
- Getting Started with React Native
- ExtJS Web應用程序開發指南第2版
- Instant Automapper
- 征服C指針(第2版)
- AngularJS UI Development
- Learning Ionic(Second Edition)
- Android項目實戰:博學谷
- 走近SDN/NFV