How to return "StatusUnauthorized" from the middleware?


#1

Hello! I create middleware that checks if the user is allowed. In case the user is not authorized - the middleware should return “StatusUnauthorized” and should not transfer control to the controller. In my case, it turns out that echo.Context is passed on and the status of 401 is overwritten by the controller. Tell me, can I not send echo.Context to the controller and return the error to the client immediately from the middleware?

private.Use(checkAuth)
private.GET("", index)

func index(c echo.Context) error {
	return c.String(http.StatusOK, "index")
}

func checkAuth(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		if err := next(c); err != nil {
			c.Error(err)
		}
		cookie, _ := c.Cookie("sessionId")
		if cookie == nil {
			return c.String(http.StatusUnauthorized, "StatusUnauthorized")
		}else{
			user := inMemorySession.Get(cookie.Value)
			if user.Username == "" {
				return c.String(http.StatusUnauthorized, "StatusUnauthorized")
			}
		}
		return nil
	}
}

In the browser: 200 “indexStatusUnauthorized”

P.S. I apologize for my English, I can try to explain it differently))
P.P.S. Found the solution: you just need to do “next ©” after all the logic.