Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks

>Solution :

on your checkUserAuth remove the

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

next() is triggered first in your middleware.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading