How to return "StatusUnauthorized" from the middleware?


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.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 {
		cookie, _ := c.Cookie("sessionId")
		if cookie == nil {
			return c.String(http.StatusUnauthorized, "StatusUnauthorized")
			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.