Golang Echo - middleware still executing next route when not returning next

I am trying to use an authentication middleware that checks if the user is currently connected and have a session before executing a route, but it seems like my middleware is not stopping the execution of the route and executing the next one even I am not calling next().

This is my code :


func checkUserAuth(next echo.HandlerFunc) echo.HandlerFunc {
    return func(c echo.Context) error {
        if err := next(c); err != nil {
            c.Error(err)
        }
        
        currSess, _ := session.Get("session", c)
        
        if userId, ok := currSess.Values["user_id"].(string); ok {
            fmt.Println("User is currently connected with id", userId);
            return next(c)
            
        } 
        // Even if middleware reaches here, it still execute the next route, why?
        return echo.ErrUnauthorized
    }
}

func main() {
    e := echo.New()

    e.Use(checkUserAuth)
    e.Use(session.Middleware(store))

    e.GET("/", func(c echo.Context) error {
        sess, _ := session.Get("session", c)
        
        fmt.Println("got session" , sess.Values["user_id"], "id", sess.ID)

        return c.String(http.StatusOK, "Hello")
    })

   e.GET("/session", func(c echo.Context) error {
        sess, _ := session.Get("session", c)
        //test
        sess.Values["user_id"] = rand.Intn(50000)
    
        sess.Save(c.Request(), c.Response())

        return c.String(http.StatusOK, "session saved")
    })

When I send a GET request to the / route, the middleware is executed correctly and reaches the return echo.ErrUnauthorized statement, but then the / still gets executed regardless and I don't get any 401 status code.

Thanks


on your checkUserAuth remove the

if err := next(c); err != nil {
    c.Error(err)
}

next() is triggered first in your middleware.