在中间件中当验证用户异常时无法通过return 的方式终止业务代码运行,
需要通过 c.Abort 进行终止
参考代码:
func CheckToken() gin.HandlerFunc {
return func(c *gin.Context) {
token, err := request.ParseFromRequest(c.Request,
request.AuthorizationHeaderExtractor,
func(token *jwt.Token) (i interface{}, e error) {
return []byte(configs.ConfInfo.SecretKey), nil
})
if err == nil {
if token.Valid {
c.Next()
} else {
c.Abort()
c.JSON(http.StatusUnauthorized, "Token is not valid")
}
} else {
c.Abort()
c.JSON(http.StatusUnauthorized, "Unauthorized access to this resource")
}
}
}