Problem Statement: - Middleware function not getting called on api hit.
Code snippets: -
func Authenticate() gin.HandlerFunc { fmt.Println("over here : ") return func(ctx *gin.Context) { headerKey := ctx.Request.Header.Get("userId") if len(headerKey) >= 0 { ctx.Next() } else { ctx.Abort() ctx.JSON( http.StatusUnauthorized, "not auth", ) } } }
router := gin.Default() // 1 try with this method router.POST("/api/some/endpoint",Authenticate() ,h.apiHnadler) // 2 try with this method router.POST("/api/some/endpoint" ,h.apiHnadler).Use(Authenticate()) // 3 try with this method router.POST("/api/some/endpoint",Authenticate() ,h.apiHnadler)
I have tried with all the above 3 methods but the middleware function never get called. The problem is that it never calls the middleware function and every time calls the handler function.
details: - go version: 1.14 gin: github.com/gin-gonic/gin v1.6.3
Comment From: bbdshow
I assume you mean you want 'over here: ' every time you hit a route, In fact, 'over here: ' only prints once during initialization.
Late execution will only return func{} So it will no longer print. You can test: if len(headerKey) >= 0 { fmt.Println("over here next!") ctx.Next() }