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 the middleware declaration
      1. @server(
      2. jwt: Auth
      3. middleware: Example // Routing middleware declaration
      4. )
      5. service search-api {
      6. @handler search
      7. get /search/do (SearchReq) returns (SearchReply)
    • Regenerate the api code
      After the generation is completed, there will be an additional middleware directory under the internal directory, which is the middleware file, and the implementation logic of the subsequent middleware is also written here.
      1. $ vim service/search/cmd/api/internal/svc/servicecontext.go
      1. type ServiceContext struct {
      2. Config config.Config
      3. Example rest.Middleware
      4. }
      5. func NewServiceContext(c config.Config) *ServiceContext {
      6. return &ServiceContext{
      7. }
      8. }
    • 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.

      1. func (m *ExampleMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
      2. return func(w http.ResponseWriter, r *http.Request) {
      3. logx.Info("example middle")
      4. next(w, r)
      5. }
      6. }
    • Start service verification
      1. {"@timestamp":"2021-02-09T11:32:57.931+08","level":"info","content":"example middle"}

    Global middleware