Skip to content

Conversation

ajilal95
Copy link

@ajilal95 ajilal95 commented Nov 6, 2022

Feature to add cross-cutting Middleware to the Router

  1. Router exports a Use() function to accepts the Middleware function.
  2. All the middleware are to be added before defining the routes.
  3. All the handles will be wrapped inside the middlewares by the Router. No need to wrap each handler inside the middleware in the application logic
  4. The Middlewares will be invoked in the order they were added to the Router.

Example usage

  router := httprouter.New()
  
  requestLogger := func (h httprouter.Handle) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, p Params) {
      doRequestLog(r)
      h(w, r, p)
    }
  }
  router.Use(requestLogger)

  testHandle1 := func(w http.ResponseWriter, req *http.Request, ps Params) {
    // handle the request
  }
  testHandle2 := func(w http.ResponseWriter, req *http.Request, ps Params) {
    // handle the request
  }

  router.GET("/test1", testHandle1)
  router.POST("/test2", testHandle2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant