Middleware
In the previous section, we demonstrated how to use jwt authentication. I believe you have mastered the basic use of jwt. In this section, let’s take a look at how to use api service middleware.
Middleware use
Here we take the search
service as an example to demonstrate the use of middleware
- Rewrite the
search.api
file and add themiddleware
declaration@server(
jwt: Auth
middleware: Example // Routing middleware declaration
)
service search-api {
@handler search
get /search/do (SearchReq) returns (SearchReply)
- Regenerate the api code
After the generation is completed, there will be an additionalmiddleware
directory under theinternal
directory, which is the middleware file, and the implementation logic of the subsequent middleware is also written here. -
$ vim service/search/cmd/api/internal/svc/servicecontext.go
type ServiceContext struct {
Config config.Config
Example rest.Middleware
}
func NewServiceContext(c config.Config) *ServiceContext {
return &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.
func (m *ExampleMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
logx.Info("example middle")
next(w, r)
}
}
- Start service verification
{"@timestamp":"2021-02-09T11:32:57.931+08","level":"info","content":"example middle"}