Middleware
In the previous section, we demonstrated how to use jwt authentication. In this section, let’s take a look at how to use API service middleware.
#
Two types of middlewaresIn go-zero, middlewares can be categorized into two groups: routing middlewares and global middlewares. A routing middleware refers to certain routes that need to implement middleware logic, which is similar to jwt and does not place the routes under jwt:xxx
Does not use middleware functions,
The scope of a global middleware is the entire service.
#
An example to demostrate how to use middlewaresHere we take the search
service as an example to demonstrate the use of middleware
#
Routing middlewareRewrite the
search.api
file and add themiddleware
declarationRegenerate the api code
After the generation is completed, there will be an additional
middleware
directory under theinternal
directory, which is the middleware file, and the implementation logic of the subsequent middleware is also written here.Improve resource dependency
ServiceContext
Write middleware logic Only one line of log is added here, with the content example middle. If the service runs and outputs example middle, it means that the middleware is in use.
Start service verification
#
Global middlewarecall rest.Server.Use
#
Call another service within the middlewarePass another service into the middleware by closure, example as below:
For full example, see: https://github.com/zeromicro/zero-examples/tree/main/http/middleware