Home > Net >  Difference between middleware chi.Use vs chi.With
Difference between middleware chi.Use vs chi.With

Time:06-17

What is the difference between chi.Use and chi.With when setting up a middleware with Chi router.

CodePudding user response:

According to the documentation of chi.Use and chi.With.

Use appends a middleware handler to the Mux middleware stack.

The middleware stack for any Mux will execute before searching for a matching route to a specific handler, which provides opportunity to respond early, change the course of the request execution, or set request-scoped values for the next http.Handler.

With adds inline middlewares for an endpoint handler.

CodePudding user response:

Use must be declared before all routes under the same group, whereas r.With allows you to "inline" middlewares.

As a matter of fact, the function signatures are different. Use returns nothing, With returns a chi.Router.

Let's say you have a route and want to add a middleware only to one of them, you would use r.With:

r.Route("/myroute", func(r chi.Router) {
    r.Use(someMiddleware) // can declare it here
    r.Get("/bar", handlerBar)
    r.Put("/baz", handlerBaz)
    // r.Use(someMiddleware) // can NOT declare it here
}

r.Route("/other-route", func(r chi.Router) {
    r.Get("/alpha", handlerBar)
    r.Put("/beta", handlerBaz)

    r.With(someMiddleware).Get("/gamma", handlerQuux)
}

In the first example, someMiddleware is declared for all sub-routes, whereas in the second example r.With allows you to add a middleware only for the /other-route/gamma route.

  • Related