I want to use grouping function after all the middelwares and routes registered. I have tried this solution but it is not suitable for me. I am using oapi generator and oapi already auto generate all the route definations in same place and with only one router. I just want to exclude or remove some middlewares from some endpoints after defined everything.
func (s *Service) registerMiddlewares() *Service {
s.gin.Use(middlewares.RequestValidatorMiddleware(s.swagger))
s.gin.Use(apmgin.Middleware(s.gin))
s.gin.Use(middlewares.CorsMiddleware())
s.gin.Use(gin.Logger())
s.gin.Use(middlewares.RequestResponseLoggerMiddleware())
// I want to exclude from /healthcheck and/or other endpoinds
s.gin.Use(middlewares.Auth())
s.gin = server.RegisterHandlers(s.gin, s.api)
return s
}
This is auto generated code and calls by RegisterHandlers
func RegisterHandlersWithOptions(router *gin.Engine, si ServerInterface, options GinServerOptions) *gin.Engine {
wrapper := ServerInterfaceWrapper{
Handler: si,
HandlerMiddlewares: options.Middlewares,
}
// all the definitions here and runs after registering all the middlewares
router.GET(options.BaseURL+"/api/v1/data/private", wrapper.GetPrivateData)
router.GET(options.BaseURL+"/healthcheck", wrapper.GetHealthcheck)
return router
}
Actual result is all the middlewares works for all endpoints. There is no way to use grouping function.
Comment From: suttapak
Do you try like this :
func (s *Service) registerMiddlewares() *Service {
s.gin.Use(middlewares.RequestResponseLoggerMiddleware())
// I want to exclude from /healthcheck and/or other endpoinds
group1 := s.gin.Group("/healthcheck",middlewares.Auth())
{
group1.GET("",func(c *gin.Context) {})
}
s.gin = server.RegisterHandlers(s.gin, s.api)
return s
}
Comment From: metinogurlu
@suttapak Thank you for your reply. But I think this is not suitable for me. Your example is a normal usage of grouping but in my scenario routes already defining in another place and if I specify some route definition before that (like yours) I am getting "handlers are already registered for path '/healthcheck'" error.
Comment From: bidianqing
What is the best way to ignore the authentication middleware from some of the routes. Please tell me what todo? thank you
app := gin.Default()
app.Use(middleware.jwt)
/* --------------------------- Public routes --------------------------- */
app.POST("/users",userHandler)
/* --------------------------- Private routes --------------------------- */
app.POST("/login",loginHandler)
app.Run()
Comment From: vkharevych-qualium
@bidianqing check here https://gin-gonic.com/zh-tw/docs/examples/using-middleware/
Comment From: bidianqing
@bidianqing check here https://gin-gonic.com/zh-tw/docs/examples/using-middleware/
@vkharevych-qualium thanks , It worked as I expected