Gin: Redirect Not Working

Created on 6 Nov 2018  路  2Comments  路  Source: gin-gonic/gin

Hello, I'm using a custom middleware that will check if user data is in the session, or not. If not in the session or nil, it will redirect to login URL. But even the user session data is nil, the middleware doesn't redirect, rather go to the next handler and causes errors. here's my code

func Authorize() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)
        loginUser := session.Get("user")
        if loginUser == nil {
            c.Redirect(http.StatusMovedPermanently, "/auth/login")
        }
    }
}

And here's my middleware position:
r.GET("/", middleware.Authorize(), indexHandler)

The loginUser is nil, but the middleware doesn't redirect to "/auth/login" rather goes to the indexHandler. Why this happens?

Most helpful comment

@cyantarek after redirecting you should abort

if loginUser == nil {
        c.Redirect(http.StatusMovedPermanently, "/auth/login")
        c.Abort()
}

All 2 comments

@cyantarek what' mean? your mean is execute it?

@cyantarek after redirecting you should abort

if loginUser == nil {
        c.Redirect(http.StatusMovedPermanently, "/auth/login")
        c.Abort()
}
Was this page helpful?
0 / 5 - 0 ratings

Related issues

wangcn picture wangcn  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

oryband picture oryband  路  3Comments

iiinsomnia picture iiinsomnia  路  3Comments

ccaza picture ccaza  路  3Comments